"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Test Go-Chi Routes with Path Variables?

How to Test Go-Chi Routes with Path Variables?

Published on 2024-11-02
Browse:572

How to Test Go-Chi Routes with Path Variables?

Testing Chi Routes with Path Variables

In go-chi, testing routes with path variables can initially pose challenges. However, by employing proper techniques, you can effectively write reliable tests.

The issue stems from the fact that path parameter values are not automatically populated in the request context when using httptest.NewRequest. This necessitates manual addition of these parameters.

One approach involves creating a new request context and manually setting the URL parameters:

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

Alternatively, it's possible to use a custom http.Handler that automatically adds the path parameter values:

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)

Remember to use the appropriate handler during testing, ensuring that both the ArticleCtx middleware and the handler itself are called.

In summary, testing routes with path variables in go-chi requires attention to populating the request context with appropriate URL parameters. Employing these techniques will enable you to write accurate and effective tests.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3