我在实现中间件时遇到问题 我想使用 negroni.Wrap
函数来验证用户位置,下面是调用处理程序的方法:
r.Handle("/users/{userID}", negroni.New(
negroni.HandlerFunc(validateTokenMiddleware),
negroni.Wrap(&userLocation),
negroni.Wrap(&userDetailHandler),
)).Methods("GET")
和 &userLocation
是包含数据库信息的结构的对象,这里当我请求处理程序时,这两个 wrap
一起执行。但我想先执行 &userlocation
,如果发生任何错误,所以 next wrap
不应该执行,如何解决这个问题。
谢谢。
最佳答案
使用具有 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)
}
关于go - 如何使用多个 negroni.Wrap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49034014/