Nested routines in Gorilla Mux

I used gorilla/mux for my routing needs. But I noticed one problem, when I install several Subrouters, this does not work.

Here is an 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 that I could delegate the filling of the router to another packet, for example user.Populate(api)

However, this does not work. It only works if I use one subprocessor in the chain.

Any ideas?

+6
source share
1 answer

I figured this out, so I'll just post it here if someone is as stupid as I am .: D

When creating a path-based routine, you should get it using PathPrefix instead of Path .

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

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

+8
source

Source: https://habr.com/ru/post/984980/


All Articles