I am implementing a Rest api using mux. After validating some parameters, I am trying to fill the missing parameters with some default values which I process later by the method that handles the request, however, I noticed that setting query parameters manually does not have any effect, unless the raw query is directly changed which is a bit hacky:
func ValidateParameters(r *http.Request) (bool) {
test := r.URL.Query().Get("test")
// if test is not provided set some default value
if test == "" {
r.URL.Query().Set("test", "Test1") //not working
r.URL.Query().Add("test", "Test2") //not working
r.URL.RawQuery = r.URL.RawQuery + "&Test=Test3" // the only method working
}
// more code
}
The handler is in another file, so I want to be able to do test := r.URL.Query().Get("test")
and get the value that I set inside ValidateParameters
which is called by the request handler, but this is not working.
any explanation to that ? any way to work around it ?
Thanks.
The problem is that r.URL.Query()
parses the url, creates the map of parameters and returns it. This is done with every .Query()
call.
This should work:
params := r.URL.Query()
params.Set("key", "value")
r.URL.RawQuery = params.Encode()