Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get params without route context? #76

Closed
gpopovic opened this issue Aug 21, 2016 · 5 comments
Closed

How to get params without route context? #76

gpopovic opened this issue Aug 21, 2016 · 5 comments

Comments

@gpopovic
Copy link

gpopovic commented Aug 21, 2016

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

@pkieltyka
Copy link
Member

@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

@gpopovic
Copy link
Author

@pkieltyka exactly what i needed. Thanks

@christopherdiehl
Copy link

christopherdiehl commented Jan 16, 2018

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

Thank you!

@soedar
Copy link

soedar commented Mar 3, 2018

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:

chi/mux_test.go

Lines 1143 to 1145 in 91a3777

rctx := NewRouteContext()
r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
rctx.URLParams.Add("name", "joe")

@gonzaloserrano
Copy link

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants