Go的HTTP中间件链是函数式装饰器链,每个中间件接收并返回http.Handler,基于ServeHTTP接口组合逻辑;中间件本身不是Handler而是Handler增强器,执行顺序为外层到内层,需手动调用next.ServeHTTP()才能延续链。

什么是 Go 的 HTTP 中间件链,它和 http.Handler 有什么关系
Go 的中间件链本质是函数式装饰器:每个中间件接收一个 http.Handler,返回一个新的 http.Handler。它不依赖框架,直接基于标准库的 http.ServeHTTP 接口组合逻辑。
关键点在于:http.Handler 只有一个方法:ServeHTTP(http.ResponseWriter, *http.Request)。所有中间件最终都必须返回满足该接口的值(通常是闭包或结构体)。
- 中间件本身不是 handler,而是 handler 的“增强器”
- 链式调用顺序 = 注册顺序 = 执行时外层到内层(类似洋葱模型)
- 不手动调用
next.ServeHTTP()就会中断链,适合做鉴权拦截
如何手写一个带日志和超时控制的中间件链
典型中间件需处理 request 生命周期的前/后逻辑。下面是一个可组合的写法,避免嵌套过深:
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf("START %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
log.Printf("END %s %s (%v)", r.Method, r.URL.Path, time.Since(start))
})
}
func timeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
done := make(chan struct{})
go func() {
next.ServeHTTP(w, r)
close(done)
}()
select {
case <-done:
case <-ctx.Done():
http.Error(w, "request timeout", http.StatusRequestTimeout)
}
})
}}
立即学习“go语言免费学习笔记(深入)”;
使用时按需叠加:
handler := loggingMiddleware(
timeoutMiddleware(5 * time.Second)(
http.HandlerFunc(yourHandler),
),
)- 注意
timeoutMiddleware是“中间件工厂”,返回中间件函数,方便传参 -
http.HandlerFunc是类型转换必需项,否则无法链式调用 - 超时中间件中不能直接用
context.WithTimeout(r.Context())后直接调用 next,必须协程+select 控制
为什么不要在中间件里修改 ResponseWriter 原始对象
标准 http.ResponseWriter 不支持写前拦截或状态码捕获。如果想记录响应状态码、Body 长度或做 gzip 压缩,必须包装它:
type responseWriterWrapper struct {
http.ResponseWriter
statusCode int
wroteHeader bool
}
func (w *responseWriterWrapper) WriteHeader(code int) {
w.statusCode = code
w.wroteHeader = true
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriterWrapper) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(b)
}
然后在中间件中使用:
func statusCodeLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wrapper := &responseWriterWrapper{
ResponseWriter: w,
statusCode: http.StatusOK,
}
next.ServeHTTP(wrapper, r)
log.Printf("Status: %d for %s", wrapper.statusCode, r.URL.Path)
})
}- 直接操作原始
w会导致WriteHeader被多次调用 panic - 自定义 wrapper 必须实现全部
http.ResponseWriter方法(包括Hijack、Flush等,如用到) - 很多第三方库(如
gorilla/handlers)内部已封装好这类 wrapper,但理解原理才能 debug
常见陷阱:中间件 panic 后无法 recover,以及 context 传递断裂
Go HTTP server 默认不 recover panic,一旦中间件 panic,整个连接会关闭且无日志。同时,若中间件创建了新 goroutine 但没传递 r.Context(),会导致超时/取消失效。
- 必须用
defer+recover包裹next.ServeHTTP调用点,尤其在外层中间件中 - 所有衍生 goroutine 都要显式传入
r.Context(),而不是用context.Background() - 不要在中间件中修改
*http.Request字段(如r.URL.Path),应使用r = r.WithContext(...)或新建 request,否则影响下游 handler - 多个中间件共用同一份
context.Valuekey 容易冲突,建议用私有类型做 key:type ctxKey string; const userIDKey ctxKey = "user_id"
中间件链看着简单,真正稳定运行要同时守住接口契约、context 生命周期、panic 边界这三条线。少一个,线上就容易静默失败。










