【发布时间】:2016-07-20 08:13:39
【问题描述】:
我正在努力让我的路由特定中间件与 httprouter 和 Negroni 一起使用。登录路由需要Middleware2,所有其他路由都需要Middleware1。
到目前为止我有:
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)
}
但现在我有点卡住了,因为网站 (https://github.com/codegangsta/negroni) 上的示例使用标准处理程序。
【问题讨论】:
-
这个答案很好地涵盖了它,基本上你添加一个 negroni 中间件链作为路由器处理程序。不利的一面是您无法直接访问
httprouter.Params -
我确实看到了这个,但由于是同一个人在回答他自己的问题,所以我不相信这是“这样做的方式”
-
我自己找不到更好的方法。这似乎是合法的,尽管我提到了那个警告。
-
顺便说一句,我最终手动将数据从请求参数复制到发布参数,以便处理程序仍然可以访问它。