1 回答
TA贡献1830条经验 获得超9个赞
最好的方法是将您的中间件封装为一个保存其状态的结构,而不仅仅是一个无状态函数。(您也可以将其包装为闭包,但结构在 IMO 中更简洁):
type MyMiddleware struct {
someval string
}
func NewMyMiddleware(someval string) *MyMiddleware {
return &MyMiddleware{
someval: someval,
}
}
func (m *MyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// Do Something with someval
fmt.Println(m.someval)
next(w, req)
}
并初始化它很简单:
n.Use(NewMyMiddleware("foo"))
编辑:也许闭包实际上很简单:
someval := foo
n.Use(negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// Do Something with someval
fmt.Println(someval)
next(w, req)
}))
或者你可以有一个返回中间件函数的函数:
func NewMiddleware(someval string) negroni.HandlerFunc {
return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// Do Something with someval
fmt.Println(someval)
next(w, req)
})
}
进而
n.Use(NewMiddleware("foo"))
- 1 回答
- 0 关注
- 140 浏览
添加回答
举报