开满天机
要实现中间件,您必须创建一个满足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-middlewarehttps://en.wikipedia.org/wiki/Decorator_pattern