1 回答

TA貢獻1786條經驗 獲得超13個贊
要實現中間件,您必須創建一個滿足http.Handler接口的函數。
實現此目的的一種方法是使用充當中間件的裝飾器函數:
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// middleware code for example logging
log.Println(r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
next論據是你的實際http.Handler。
下面是一個更完整的例子:
func main() {
var handler http.HandlerFunc = testHandler
// Here the handler is wrapped with the middleware
http.Handle("/test", middleware(handler))
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// middleware code for example logging
log.Println(r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
func testHandler(w http.ResponseWriter, r *http.Request) {
// your handler code
}
此模式有時稱為裝飾器模式,有關更多信息,請參閱以下鏈接:
https://www.alexedwards.net/blog/making-and-using-middleware
https://en.wikipedia.org/wiki/Decorator_pattern
- 1 回答
- 0 關注
- 134 瀏覽
添加回答
舉報