Reversing a Subrouter in Gorilla / Mux

Ecognium :

I would like to get the path for a named subroute but my code below does not work. When I try to use the same logic on a non-subroute, it works fine. How do I get the path of a named subroute?

router = mux.NewRouter() // this is a global variable
home := router.Path("/home").Subrouter()
home.Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
home.Methods("POST").HandlerFunc(c.PostHomeHandler)

p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

The above gives this error:

panic: mux: route doesn't have a host or path

Now if I do router.HandleFunc("/home", c.GetHomeHandler).Name("home"), it works just fine.

Appreciate your help.

Update:

This is a reasonable workaround but it avoids creating a Subroute. It is fine for the example I had above but probably not ideal as you will not get all the benefits of a Subroute.

router.Path("/home").Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
router.Path("/home").Methods("POST").HandlerFunc(c.PostHomeHandler)

Thanks!

John Adams :

I believe you'd need to specify your subroute with a PathPrefix, then in order to support /home and /home/ enable StrictSlash (due to this issue)

router := mux.NewRouter() 
home := router.PathPrefix("/home").Subrouter().StrictSlash(true)
home.Path("/").Methods("GET").HandlerFunc(GetHomeHandler).Name("home")
home.Path("/post/").Methods("POST").HandlerFunc(PostHomeHandler).Name("home-post")


p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

p, err = home.Get("home-post").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related