Using the code below, when I access / test 2, it answers 404 - not found. / test 1 is working correctly. Why is this? Is nesting not allowed even though routers implement the http.Handler interface?
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { mainRouter := mux.NewRouter() subRouter := mux.NewRouter() mainRouter.HandleFunc("/test1", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test1") }) subRouter.HandleFunc("/test2", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test2") }) mainRouter.Handle("/", subRouter) http.ListenAndServe(":9999", mainRouter) }
EDIT:
My main goal was to add some initial work, which would be common to all routes in the subRouter and only for them. To be more specific, I would like to use Negroni as my intermediate logger. Negroni has an example of adding middleware to a route group:
router := mux.NewRouter() adminRoutes := mux.NewRouter() // add admin routes here Create a new negroni for the admin middleware router.Handle("/admin", negroni.New( Middleware1, Middleware2, negroni.Wrap(adminRoutes), ))
Negroni basically executes ServeHTTP methods for each argument, since they all implement http.Handler. It runs them in order, so the router routes will be the last.
I am familiar with the concept of Subrouter in Mux, but AFAIK I cannot use it in the same way as the example above, in particular, I can not enter anything between mainRouter and its Subrouter . This is why nesting looks more flexible.
source share