Skip to content

Instantly share code, notes, and snippets.

@jasonwbarnett
Created May 29, 2015 19:19
Show Gist options
  • Save jasonwbarnett/2ba8088f49d0776a24cf to your computer and use it in GitHub Desktop.
Save jasonwbarnett/2ba8088f49d0776a24cf to your computer and use it in GitHub Desktop.
This is an example of how we might nest multiple mux.Routers. This is especially useful if we want to later wrap our nested router with Negroni.
package hello
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func init() {
// Create the "root" router, if you will...
r := mux.NewRouter().StrictSlash(true)
// Create your "Subrouter" dedicated to /api which will use the PathPrefix
apiRouter := mux.NewRouter().PathPrefix("/api").Subrouter().StrictSlash(true)
// This step is where we connect our "root" router and our "Subrouter" together.
r.PathPrefix("/api").Handler(apiRouter)
// Define "root" routes using r
r.HandleFunc(genHandleFunc("/", "root of site"))
r.HandleFunc(genHandleFunc("/home", "home"))
// Define "Subrouter" routes using apiRouter
apiRouter.HandleFunc(genHandleFunc("/", "root of API, /api"))
apiRouter.HandleFunc(genHandleFunc("/v1/", "root of API V1, /api/v1"))
apiRouter.HandleFunc(genHandleFunc("/v1/resourceabc", "API V1 - resourceabc, /api/v1/resourceabc"))
/* Finally we pass our "root" router to the net/http library. The "root" router will contain all
of the routes for /api also.
*/
http.Handle("/", r)
}
// Silly function to quickly generate a HandleFunc
func genHandleFunc(p string, msg string) (path string, f func(http.ResponseWriter, *http.Request)) {
path = p
f = func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%v\n", msg)
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment