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 關注
- 164 瀏覽
添加回答
舉報