第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用路徑變量測試 Chi 路徑

使用路徑變量測試 Chi 路徑

Go
吃雞游戲 2023-06-05 17:33:59
我在測試我的 go-chi 路線時遇到問題,特別是帶有路徑變量的路線。運行服務器go run main.go工作正常,對路徑變量的路由請求按預期運行。當我對路由運行測試時,我總是收到 HTTP 錯誤:Unprocessable Entity。注銷 發(fā)生的情況后articleID,似乎articleCtx無法訪問路徑變量。不確定這是否意味著我需要articleCtx在測試中使用,但我已經(jīng)嘗試ArticleCtx(http.HandlerFunc(GetArticleID))并得到錯誤:panic: interface conversion: interface {} is nil, not *chi.Context [recovered]    panic: interface conversion: interface {} is nil, not *chi.Context運行服務器:go run main.go測試服務器:go test .我的來源:// main.gopackage mainimport (    "context"    "fmt"    "net/http"    "strconv"    "github.com/go-chi/chi")type ctxKey struct {    name string}func main() {    r := chi.NewRouter()    r.Route("/articles", func(r chi.Router) {        r.Route("/{articleID}", func(r chi.Router) {            r.Use(ArticleCtx)            r.Get("/", GetArticleID) // GET /articles/123        })    })    http.ListenAndServe(":3333", r)}// ArticleCtx gives the routes using it access to the requested article ID in the pathfunc ArticleCtx(next http.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        articleParam := chi.URLParam(r, "articleID")        articleID, err := strconv.Atoi(articleParam)        if err != nil {            http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)            return        }        ctx := context.WithValue(r.Context(), ctxKey{"articleID"}, articleID)        next.ServeHTTP(w, r.WithContext(ctx))    })}// GetArticleID returns the article ID that the client requestedfunc GetArticleID(w http.ResponseWriter, r *http.Request) {    ctx := r.Context()    articleID, ok := ctx.Value(ctxKey{"articleID"}).(int)    if !ok {        http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)        return    }    w.Write([]byte(fmt.Sprintf("article ID:%d", articleID)))}
查看完整描述

4 回答

?
蝴蝶不菲

TA貢獻1810條經(jīng)驗 獲得超4個贊

有一個類似的問題,雖然我直接對處理程序進行單元測試。httptest.NewRequest基本上,當使用強制您手動添加時,url 參數(shù)似乎不會自動添加到請求上下文中。


以下內容對我有用。


w := httptest.NewRecorder()

r := httptest.NewRequest("GET", "/{key}", nil)


rctx := chi.NewRouteContext()

rctx.URLParams.Add("key", "value")


r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))


handler := func(w http.ResponseWriter, r *http.Request) {

? ? value := chi.URLParam(r, "key")

}

handler(w, r)

全部歸功于soedar?=)



查看完整回答
反對 回復 2023-06-05
?
拉風的咖菲貓

TA貢獻1995條經(jīng)驗 獲得超2個贊

我對命名路徑變量有同樣的問題。我能夠解決它為我的測試設置路由器。go-chi 測試顯示了一個好的樣本。

查看完整回答
反對 回復 2023-06-05
?
慕哥6287543

TA貢獻1831條經(jīng)驗 獲得超10個贊

現(xiàn)在可能遲到了 :) 但也許其他人會發(fā)現(xiàn)它有用。


我遇到了同樣的問題,并希望將我的測試結構化為一個片段,所以我最終創(chuàng)建了一個“幫助程序”函數(shù),以便向請求添加所需的 chi 上下文:


func AddChiURLParams(r *http.Request, params map[string]string) *http.Request {

    ctx := chi.NewRouteContext()

    for k, v := range params {

        ctx.URLParams.Add(k, v)

    }


    return r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, ctx))

}

同樣,正如@Ullauri 所提到的,解決方案的所有功勞都歸功于soedar。


但是有了這個函數(shù),你就可以像這樣在切片中很好地使用它:


{

    name: "OK_100",

    rec:  httptest.NewRecorder(),

    req: AddChiURLParams(httptest.NewRequest("GET", "/articles/100", nil), map[string]string{

        "id": "100",

    }),

    expectedBody: `article ID:100`,

},

希望這可以幫助!:)


查看完整回答
反對 回復 2023-06-05
?
阿晨1998

TA貢獻2037條經(jīng)驗 獲得超6個贊

在您指導定義 path 之后main的用法,但在您的測試中您只是直接使用。ArticleCtx/articlesArticleCtx

您的測試請求不應包含/articles,例如:

httptest.NewRequest("GET", "/1", nil)


查看完整回答
反對 回復 2023-06-05
  • 4 回答
  • 0 關注
  • 228 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號