Chi: How to get params without route context?

Created on 21 Aug 2016  路  5Comments  路  Source: go-chi/chi

Is it possible to get param from the handler without route context?

When i'm testing handler, i need to be able to retrieve params with chi.URLParam(), but when i try to do it outside router, i'm getting panic

Most helpful comment

I've recently ran into the same issue. For posterity, this should work:

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", 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) {
    key := chi.URLParam(r, "key") // "value"
}
handler(w, r)

Adapted from: https://github.com/go-chi/chi/blob/91a3777c41c3d3493a446f690b572d93a76cba73/mux_test.go#L1143-L1145

All 5 comments

@gpopovic can you show me the test code for that handler?

it's possible to go about it a few ways, but if you're testing just a single handler that is trying to fetch URLParams from a request, then you need to make sure the URLParams object is available on the request chain. Have a look at https://github.com/pressly/chi/blob/master/mux_test.go#L810-L829

@pkieltyka exactly what i needed. Thanks

@pkieltyka can you please elaborate? I don't understand how to replicate the URLParams in the router context.

Thank you!

I've recently ran into the same issue. For posterity, this should work:

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", 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) {
    key := chi.URLParam(r, "key") // "value"
}
handler(w, r)

Adapted from: https://github.com/go-chi/chi/blob/91a3777c41c3d3493a446f690b572d93a76cba73/mux_test.go#L1143-L1145

@soedar solution works, thanks a lot!

Anyway I don't think chi should panic if the context is not available like it does with:

panic: interface conversion: interface {} is nil, not *chi.Context [recovered]
    panic: interface conversion: interface {} is nil, not *chi.Context

Maybe if there is no context URLParam() could return empty string instead?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jsadwith picture jsadwith  路  6Comments

EmielM picture EmielM  路  9Comments

valsor picture valsor  路  5Comments

chenjie4255 picture chenjie4255  路  11Comments

netsharec picture netsharec  路  6Comments