2

I'm struggling to get my route specific middleware working with httprouter and Negroni. The login route requires Middleware2 and all the other routes require Middleware1.

So far I have:

func Main() {
    router := httprouter.New()
    protectedRoutes := httprouter.New()

    DefineRoutes(router)
    DefineProtectedRoutes(protectedRoutes)

    //This is the block that I'm unsure about
    //How can I introduce Middleware2 for a specific route?
    n := negroni.New()
    n.Use(negroni.HandlerFunc(Middleware1))
    n.UseHandler(router)


    n.Run(":5000")
}

func DefineRoutes(router *httprouter.Router) {
    router.POST("/v1/users/authenticate", UserLogin)
    router.POST("/v1/users/authorize", UserLogin)
    router.POST("/v1/users/logout", UserLogout)
}

func DefineProtectedRoutes(router *httprouter.Router) {
    router.POST("/v1/users/login", UserLogin)
}

but now I'm a bit stuck as the examples on the site (https://github.com/codegangsta/negroni) use the standard handlers.

tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • 1
    possible duplicate of [Route-specific Middlewares with Negroni](http://stackoverflow.com/questions/28418168/route-specific-middlewares-with-negroni) – Not_a_Golfer May 20 '15 at 13:14
  • that answer covers it pretty well, basically you add a negroni middleware chain as a router handler. The down side is that you lose direct access to the `httprouter.Params` – Not_a_Golfer May 20 '15 at 13:15
  • I did see this one but as it was the same person answering his own question I wasn't convinced it was "the way to do it" – tommyd456 May 20 '15 at 13:15
  • I couldn't find a better way to do it myself. It seems legit, although with that caveat I mentioned. – Not_a_Golfer May 20 '15 at 13:16
  • BTW I ended up manually copying data from the request params to the post params so that the handlers can still access it. – Not_a_Golfer May 20 '15 at 13:17
  • How did you manage to copy the request params over so the middleware handlers had access? Do you happen to have a gist somewhere I could look at? – cat-t Oct 03 '16 at 00:21

1 Answers1

0

Not sure if anyone is still looking for an answer. I think params can be retrieved by calling the router.Lookup function. Here is what I did:

_, params, _ :=  router.Lookup("GET", req.URL.Path)

where router is an instance of httprouter.Router

showdev
  • 28,454
  • 37
  • 55
  • 73
Unni
  • 1