I have a very simple Go server code setup with mux
and when I use curl
with GET
request params (localhost:8080/suggestions/?locale=en
), I get 301 status code (Move permanently). But when there's no get parameters, it's working just fine.
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/suggestions", handleSuggestions).Methods("GET")
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
Can somebody shed me a light on this.Thanks
That's simply because you registered the path /suggestions
(note: there is no trailing slash), and you call the URL localhost:8080/suggestions/?locale=en
(there is a trailing slash after /suggestions
).
You router detects that there's a registered path which would match the requested path without the trailing slash (based on your Router.StrictSlash()
policy), so it sends a redirect which when followed would lead you to a valid, registered path.
Simply use a URL without trailing slash after suggestions
:
localhost:8080/suggestions?locale=en
go doc mux.StrictSlash states:
func (r *Router) StrictSlash(value bool) *Router
StrictSlash defines the trailing slash behavior for new routes. The initial
value is false.
When true, if the route path is "/path/", accessing "/path" will redirect to
the former and vice versa. In other words, your application will always see
the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not match
this route and vice versa.
Special case: when a route sets a path prefix using the PathPrefix() method,
strict slash is ignored for that route because the redirect behavior can't
be determined from a prefix alone. However, any subrouters created from that
route inherit the original StrictSlash setting.
So to avoid the redirects you can either mux.NewRouter().StrictSlash(false)
which is equivalent to mux.NewRouter()
or use a URL with a trailing slash i.e. router.HandleFunc("/suggestions/", handleSuggestions).Methods("GET")