Go中间件链通过函数式包装http.Handler实现,预处理逻辑在handler前执行(如鉴权),后处理在后执行(如日志、响应头),推荐用context传递数据并封装Chain工具链式调用。
在 Go 中实现中间件链,核心是利用函数式编程思想:每个中间件接收一个 http.Handler 并返回一个新的 http.Handler,形成可组合、可复用的处理链。请求预处理(如日志、鉴权、限流)放在 handler 执行前,后处理(如响应头注入、耗时统计)放在 handler 执行后。
Go 的 http.Handler 接口只有一个方法:ServeHTTP(http.ResponseWriter, *http.Request)。中间件本质是“包装器”:
mw3(mw2(mw1(handler)))
以下为常见场景的中间件写法,注意顺序影响执行时机:
next.ServeHTTP 后读取状态码(需用 ResponseWriter 包装器捕获)
next.ServeHTTP,中断链路
ctx 或 request 的 context.WithValue
next.ServeHTTP 后调用 w.Header().Set(...)
中间件间共享数据推荐用 request.Context(),而非全局变量或自定义 struct:
r = r.WithContext(context.WithValue(r.Context(), key, value)) 注入数据r.Context().Value(key) 获取type userIDKey struct{})避免冲突手动嵌套 mw1(mw2(mw3(handler))) 易出错且难维护,可封装 Chain 工具:
type Middl
eware func(http.Handler) http.Handler
func Chain(h http.Handler, mws ...Middleware) http.Handler
mws[0](mws[1](...mws[n](h)...))),符合直觉http.ListenAndServe(":8080", Chain(myHandler, logging, auth, headers))