How to filter some path from mux. Gorilla.Router
I would like to match only some of the routes from mux.Router and use the same handler for all the others. How can i do this?
ie: having the following paths:
/general/baz/bro /general/foo/bar /general/unknown
I would like to map the first one to a specific handler and all the others to the default handler.
I have tried something like:
r.Methods("GET").PathPrefix("/general").Handler(defaultHandler)
r.Methods("GET").Path("/general/baz/bro").Handler(bazBroHandler)
I expected bazBroHandler to handle the path /general/baz/bro
, and defaultHandler to handle everything else starting with/general
+3
source to share
2 answers
One way to achieve this is to use MatcherFunc . In MatcherFunc
compare / check the incoming request Path
, that is:
//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)
0
source to share