使用路径变量测试 Chi 路由
在 go-chi 中,使用路径变量测试路由最初可能会带来挑战。但是,通过采用适当的技术,您可以有效地编写可靠的测试。
问题源于以下事实:使用 httptest.NewRequest 时,路径参数值不会自动填充到请求上下文中。这需要手动添加这些参数。
一种方法涉及创建新的请求上下文并手动设置 URL 参数:
<code class="go">// Request & new request context creation req := httptest.NewRequest("GET", "/articles/123", nil) reqCtx := chi.NewRouteContext() reqCtx.URLParams.Add("articleID", "123") // Setting custom request context with Route Context Key rctxKey := chi.RouteCtxKey req = req.WithContext(context.WithValue(req.Context(), rctxKey, reqCtx))</code>
或者,可以使用自定义 http.Handler自动添加路径参数值:
<code class="go">type URLParamHandler struct { Next http.Handler } func (h URLParamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { rctx := chi.NewRouteContext() for key, val := range r.URL.Query() { rctx.URLParams.Add(key, val[0]) } r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx)) h.Next.ServeHTTP(w, r) }</code>
<code class="go">// Middleware usage in test handler := URLParamHandler{Next: ArticleCtx(GetArticleID)} handler.ServeHTTP(rec, req)</code>
记住在测试过程中使用适当的处理程序,确保 ArticleCtx 中间件和处理程序本身都被调用。
总而言之,在 go-chi 中使用路径变量测试路由需要注意使用适当的 URL 参数填充请求上下文。采用这些技术将使您能够编写准确且有效的测试。
以上是如何使用路径变量测试 Go-Chi 路由?的详细内容。更多信息请关注PHP中文网其他相关文章!