2
votes

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.

1
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.ParamsNot_a_Golfer
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
I couldn't find a better way to do it myself. It seems legit, although with that caveat I mentioned.Not_a_Golfer
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

1 Answers

0
votes

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