mux: Can't create "root" route on a subrouter

r := mux.NewRouter()
sr := r.PathPrefix("/foo")
sr.Path("/").HandlerFunc(...)

// GET /foo/ -> OK
// GET /foo -> 404 Not Found

I can’t find a way to get the second request to work. I thought StrictSlash might help, but it doesn’t. Any suggestions?

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 16 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Thanks for the reply. My example was slightly wrong, it seems. Have you tried your example? Because that’s what I was actually doing and it doesn’t work quite how I expect it to.

The behaviour is specifically just for Path("/") on a subrouter, it behaves differently to Path("/") on a top-level router.

Using your example:

r := mux.NewRouter()
sr := r.PathPrefix("/foo").Subrouter()
sr.Path("/").HandlerFunc(...)
GET http://localhost/foo => 404
GET http://localhost/foo/ => 200

When not using a top-level router:

r := mux.NewRouter()
r.Path("/").HandlerFunc(...)
GET http://localhost => 200
GET http://localhost/ => 200

This makes it difficult for me to make nesting independent routes. I want to be able to define something like:

package mymodule

func Routes(r *mux.Router) {
  r.Path("/").Handler(rootHandler)
  r.Path("/{id}").Handler(idHandler)
}

// elsewhere
mymodule.Routes(r.PathPrefix("/v1/abc").Subrouter())

Is there any update on this?

I have the situation where I want to handle just the path prefix for a subrouter, but I can’t unless there’s a trailing /. I think that’s the same as this issue.

s := r.PathPrefix("/path")
s.Handle("", handler) // Here I want to set the handler for "/path" alone.

Having a similar issue.
Router with strictslash = true, and seems to properly propagate to subrouter However, the path “/” on the sub redirects OK, but POSTs are being redirected to GET, which is bad

Is this a known issue?

Just for clarity: you’re not using a Subrouter that I can see anywhere…PathPrefix doesn’t create a Subrouter, Subrouter does. Try doing this instead:

r := mux.NewRouter()
sr := r.PathPrefix("/foo").Subrouter()
sr.Path("/").HandlerFunc(...)