I'm having a difficult time understanding how to use negroni and httprouter together.
I have a couple of public routes, such as /api/v1/ping
I have a bunch of private routes that need auth middleware, such as /api/v1/user
If I want negroni Common middleware for all of my routes, but I want to apply the auth middleware and others to only the private routes, how can I set this up?
v1.router := httprouter.New()
v1.router.GET("/api/v1/ping", v1.ping)
v1.router.GET("/api/v1/user", v1.getUsers)
n := negroni.Classic()
n.UseHandler(v1.router)
http.ListenAndServe(port, n)
You could try and adapt the technique described in "Path Prefix Middleware in Go ", which is using net/http/#ServeMux
, with another router (gorilla/mux
), but should be valid for julienschmidt/httprouter
as well:
Specifying middleware based on route prefixes
This is where the magic happens, and it is also where things get confusing.
The easiesy way I have found to specify middleware for a path prefix is to setup a second muxer (we use the
sirMuxalot
variable for ours below) that has the path prefixes we want to apply middleware to, and to then pass in our original router wrapped in some middleware for those routes.This works because the
sirMuxalot
router won’t ever call the middleware-wrapped router unless the path prefix we define gets matched with the incoming web request’s path.sirMuxalot := http.NewServeMux() sirMuxalot.Handle("/", r) sirMuxalot.Handle("/api/", negroni.New( negroni.HandlerFunc(APIMiddleware), negroni.Wrap(r), )) sirMuxalot.Handle("/dashboard/", negroni.New( negroni.HandlerFunc(DashboardMiddleware), negroni.Wrap(r), )) n := negroni.Classic() n.UseHandler(sirMuxalot) http.ListenAndServe(":3000", n)