1 回答
TA贡献1824条经验 获得超6个赞
这是 Go 的一个基本示例net/http:
func main() {
r := http.NewServeMux()
r.HandleFunc("/some-route", SomeHandler)
// Wrap your *ServeMux with a function that looks like
// func SomeMiddleware(h http.Handler) http.Handler
http.ListenAndServe("/", YourMiddleware(r))
}
中间件可能是这样的:
func YourMiddleware(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Do something with the response
w.Header().Set("Server", "Probably Go")
// Call the next handler
h.ServeHTTP(w, r)
}
// Type-convert our function so that it
// satisfies the http.Handler interface
return http.HandlerFunc(fn)
}
如果您有很多要链接的中间件,像alice这样的包可以简化它,这样您就不会Wrapping(AllOf(YourMiddleware(r))))那样了。您也可以编写自己的助手 -
func use(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
for _, m := range middleware {
h = m(h)
}
return h
}
// Example usage:
defaultRouter := use(r, handlers.LoggingHandler, csrf.Protect(key), CORSMiddleware)
http.ListenAndServe(":8000", defaultRouter)
- 1 回答
- 0 关注
- 234 浏览
添加回答
举报