首頁  >  文章  >  後端開發  >  如何使用路徑變數測試 Go-Chi 路由:解決無法處理的實體錯誤

如何使用路徑變數測試 Go-Chi 路由:解決無法處理的實體錯誤

Linda Hamilton
Linda Hamilton原創
2024-10-27 06:59:29325瀏覽

How to Test Go-Chi Routes with Path Variables:  Resolving Unprocessable Entity Errors

使用路徑變數測試Chi 路由:故障排除和解決方案

在go-chi 中,路由內的路徑變數存取由中間件函數(如文章Ctx.測試此類路由時,必須在HTTP 請求的上下文中手動設定路徑變數。這是因為httptest 套件不會自動填入上下文。

問題:
要測試使用路徑變數的路由,需要使用httptest.NewRequest 建立測試請求。

解決方案:

解決方案在於手動在將路徑參數傳遞給處理程序之前將路徑參數添加到請求上下文中:

透過將路徑變數新增至請求的上下文中,ArticleCtx 中間件可以正確檢索文章ID,從而解決Unprocessable Entity 錯誤。框架來簡化單元測試。 🎜>
<code class="go">// Create a context with the path variable
req := httptest.NewRequest("GET", "/articles/1", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("articleID", "1")

// Set the RouteCtx in the request context
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))

// Execute the handler with the modified request
rec := httptest.NewRecorder()
ArticleCtx(http.HandlerFunc(GetArticleID)).ServeHTTP(rec, req)</code>
實作其他測試以涵蓋各種場景,例如處理錯誤請求或路線級錯誤。

以上是如何使用路徑變數測試 Go-Chi 路由:解決無法處理的實體錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn