Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting subrouters in Gorilla Mux

I've been using gorilla/mux for my routing needs. But I noticed one problem, when I nest multiple Subrouters it doesn't work.

Here is the example:

func main() {
    r := mux.NewRouter().StrictSlash(true)
    api := r.Path("/api").Subrouter()
    u := api.Path("/user").Subrouter()
    u.Methods("GET").HandleFunc(UserHandler)
    http.ListenAndServe(":8080", r)
}

I wanted to use this approach so I can delegate populating the router to some other package, for example user.Populate(api)

However this doesn't seem to work. It works only if I use single Subrouter in the chain.

Any ideas?

like image 771
Kortemy Avatar asked Apr 11 '15 08:04

Kortemy


2 Answers

I figured it out, so I'll just post it here in case someone is as stupid as I was. :D

When creating path-based subrouter, you have to obtain it with PathPrefix instead of Path.

r.PathPrefix("/api").Subrouter()

Use r.Path("/api") only when attaching handlers to that endpoint.

like image 150
Kortemy Avatar answered Nov 20 '22 12:11

Kortemy


For those who are struggling to split between auth and noauth routes, the following works fine for me:

r := mux.NewRouter()

noAuthRouter := r.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
    return r.Header.Get("Authorization") == ""
}).Subrouter()

authRouter := r.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
    return true
}).Subrouter()

Then you can apply middleware for authRouter only

like image 1
mikhailb Avatar answered Nov 20 '22 12:11

mikhailb