-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
Custom context for mux.Vars #187
Comments
The custom, private types exist so that other packages won't clobber over it. If any other user was using |
Ah. In that case, could we expose |
Would the solution in #167 not work for you? Directly mutating internal state should be avoidable. |
Of course it would work, but I'm not trying to handle the response or even care about the route itself. I'm just pulling params from the It would be so much easier for people to use something like: request, _ := http.NewRequest("PATCH", "", nil)
ctx := context.WithValue(request.Context(), 0, map[string]string{
"param1": param1,
"param2": param2,
})
data := mapParams(request.WithContext(ctx))
// assertions to check data Verses having all of this to achieve the same result: router := mux.NewRouter()
router.HandleFunc("/{param1}/{param2}", func (response http.ResponseWriter, request *http.Request) {
data := mapParams(request)
// assertions to check data
})
ts := httptest.NewServer(router)
defer ts.Close()
url := fmt.Sprintf("%s/%s/%s", ts.URL, param1, param2)
request, _ := http.NewRequest("PATCH", url, nil)
c := &http.Client{}
response, e := c.Do(request)
if e != nil {
t.Error(e)
} |
If you're testing multiple routes via table-driven testing, I would think The benefit to not just injecting into the context is that you also ensure
|
I'm not testing routes at all. I would just like to be able to force a context with params during testing instead of setting up a router, handler, httptest server, http client, and then finally be able to send my request for testing. I'm not sure that's a benefit because I highly doubt most people will ever want to modify the context during runtime in the first place. |
I'm not testing routes either. Instead, I have collections of That being said, I do see my doing this as a code smell in my application. I guess that it would be preferable to have middleware that passes @elithrar - do you have any other suggestions on how to test functions that use |
Hey we can close this now 🎉 since this PR has been merged. To set context vars you just need to do the following:
|
Is there a particular reason that
varsKey
androuteKey
are using thecontextKey
type? https://github.com/gorilla/mux/blob/master/mux.go#L322-L327This causes problems when attempting to use
request.WithContext(context.WithValue(request.Context(), 0, map[string]string{...}))
for testing route params becausemux.Vars
is looking forcontextKey(0)
as the key rather thanint(0)
.The text was updated successfully, but these errors were encountered: