I would like to match only some routes from a mux.Router, and use the same handler for all the others. How can I do this?
i.e.: having these paths:
/general/baz/bro
/general/foo/bar
/general/unknown
I would like to match the first with a specific handler, and all the others with a default handler.
I've tried with no success something like:
r.Methods("GET").PathPrefix("/general").Handler(defaultHandler)
r.Methods("GET").Path("/general/baz/bro").Handler(bazBroHandler)
I was expecting the bazBroHandler handling the /general/baz/bro
path, and the defaultHandler all the other starting with /general
In the end I've just realized that I needed to invert the order:
r.Methods("GET").Path("/general/baz/bro").Handler(bazBroHandler)
r.Methods("GET").PathPrefix("/general").Handler(defaultHandler)
now everything is working!
One way to achieve this is by using MatcherFunc. In the MatcherFunc
, compare/verify the incoming request Path
, i.e.:
//Default handler
r.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
return r.URL.Path != "/general/baz/bro" && strings.HasPrefix(r.URL.Path, "/general") && r.Method == "GET"
}).Handler(defaultHandler)
//Specific handler
r.Methods("GET").Path("/general/baz/bro").Handler(bazBroHandler)