如何使用多个negroni.Wrap()

时间:2018-02-28 16:16:39

标签: go

我有一个实现中间件的问题我想使用negroni.Wrap函数来验证用户位置,下面一个用于调用处理程序的是我的路径:

r.Handle("/users/{userID}", negroni.New(
        negroni.HandlerFunc(validateTokenMiddleware),
        negroni.Wrap(&userLocation),
        negroni.Wrap(&userDetailHandler),
    )).Methods("GET")

&userLocation是包含数据库信息的结构的对象,这里当我请求处理程序时,那时wrap同时执行。但我希望首先执行&userlocation,如果发生任何错误,则不应执行next wrap,如何解决此问题。

感谢。

1 个答案:

答案 0 :(得分:0)

使用具有ServeHttp方法的中间件,该方法将使用userDetailHandler作为中间件内的接收器进行调用。并将中间件中的db结构作为参数传递。你应该使用单包。

r.Handle("/users/{userID}", negroni.New(
        negroni.HandlerFunc(validateTokenMiddleware),
        negroni.Wrap(userDetailHandler.Middleware(&userLocation)),
    )).Methods("GET")

func (userDetailHandler *UserDetailHandler)Middleware(res http.ResponseWriter, req *http.Request, userLocation *userLocation){
   // use your serve Http inside this
   userDetailHandler.ServeHttp(res, req)
}