首頁 > 後端開發 > Golang > 主體

如何使用路徑變數測試 Go-Chi 路由?

Barbara Streisand
發布: 2024-10-27 12:14:30
原創
291 人瀏覽過

How to Test Go-Chi Routes with Path Variables?

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!