」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用路徑變數測試 Go-Chi 路由?

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

發佈於2024-11-02
瀏覽:139

How to Test Go-Chi Routes with Path Variables?

使用路徑變數測試 Chi 路由

在 go-chi 中,使用路徑變數測試路由最初可能會帶來挑戰。但是,透過採用適當的技術,您可以有效地編寫可靠的測試。

問題源自於以下事實:使用 httptest.NewRequest 時,路徑參數值不會自動填入請求上下文。這就需要手動新增這些參數。

一種方法涉及創建新的請求上下文並手動設定 URL 參數:

// 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))

或者,可以使用自動新增路徑參數值的自訂http.Handler:

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)
}
// Middleware usage in test
handler := URLParamHandler{Next: ArticleCtx(GetArticleID)}
handler.ServeHTTP(rec, req)

記住在測試過程中使用適當的處理程序,確保 ArticleCtx 中間件和處理程序本身都被呼叫。

總之,使用路徑變數測試路由在 go-chi 中需要注意使用適當的 URL 參數填充請求上下文。採用這些技術將使您能夠編寫準確且有效的測試。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3