Nested Gorilla Mux router does not work

kars7e picture kars7e · Aug 3, 2014 · Viewed 7.9k times · Source

Using code below, when I access /test2 it responds with 404 - not found. /test1 works correctly. Why is that? Is nesting not allowed despite the fact that routers implement 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 for all routes in subRouter, and only for them. To be even more specific, I would like to use Negroni as my middleware orchiestrator. On the Negroni website there is an example of adding middleware to the group of routes:

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 of every argument, since all of them implement http.Handler. It executes them in order, so router routes will be last.

I'm familiar with the concept of Subrouter in Mux, but AFAIK I can't use it in similar fashion as example above, in particular, I can't inject anything between mainRouter and its Subrouter. This is why nesting looks more flexible.

Answer

Paulius picture Paulius · Dec 5, 2014

I know this question is somewhat old, but I have spent some time figuring out how handlers and matching work in go. You can see my experiment code here.

Basically, you can get the effect you want with code like this:

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")
    })

    // in mux, you need to register subrouter
    // with the same path that the handlers in
    // it are matching
    mainRouter.Handle("/test2", subRouter)

    // if your subrouter has handlers that match
    // other sub paths - you also need to do this
    mainRouter.Handle("/test2/{_dummy:.*}", subRouter)

    http.ListenAndServe(":9999", mainRouter)
}

I hope this helps someone.