使用路徑變數測試 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中文網其他相關文章!