go http中间件本质是接收并返回http.handler的函数链,需显式调用next.servehttp,用responsewriter包装器修改响应,闭包传参确保并发安全,recover必须置于最外层,避免context.withvalue滥用。

中间件本质是函数链,不是装饰器
Go 的 HTTP 中间件没有语言级支持,它只是 http.Handler 或 http.HandlerFunc 的嵌套封装。你写的每个中间件都该接收一个 http.Handler 并返回一个新的 http.Handler,而不是“给路由加个注解”那种抽象。
常见错误是把中间件写成独立的 func(http.ResponseWriter, *http.Request),这样无法串起来;也有人试图用闭包“劫持” next 但漏掉 next.ServeHTTP(w, r) 调用,导致请求静默终止。
- 必须显式调用
next.ServeHTTP(w, r),否则后续中间件和最终 handler 不会执行 - 不要在中间件里直接写
w.WriteHeader()后又调用next,这会触发http: multiple response.WriteHeader calls - 如果要修改响应(如压缩、CORS),得用
ResponseWriter包装器,而非直接操作原始w
用闭包传参比全局配置更安全
比如日志中间件需要服务名、调试开关,别用 var debug = true 这种包级变量——并发下可能被意外改写。正确做法是让中间件工厂函数接收参数并闭包捕获:
func LoggingService(name string, debug bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if debug {
log.Printf("[%s] %s %s", name, r.Method, r.URL.Path)
}
next.ServeHTTP(w, r)
})
}
}
这样每个 LoggingService("api", true) 实例都有独立状态,可复用、可测试、无副作用。
立即学习“go语言免费学习笔记(深入)”;
- 避免使用
init()初始化中间件依赖(如数据库连接),应由主程序注入 - 若需共享资源(如 Redis 客户端),通过闭包传入,而非在中间件内部
redis.NewClient() - 不要在闭包里启动 goroutine 监听信号或定时任务——中间件实例可能被反复创建
panic 恢复必须在最外层中间件做
Go HTTP server 遇到 panic 默认会打印堆栈并关闭连接,但不会返回 500 响应。如果你把 recover() 放在某个业务中间件里,上层中间件(如 CORS、JWT)已经写了 header,再 recover 就晚了。
正确位置是整个 handler 链的最外层,也就是最后被注册的那个中间件:
func Recover() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Printf("PANIC: %+v", err)
}
}()
next.ServeHTTP(w, r)
})
}
}
- 恢复后不能继续调用
next.ServeHTTP,否则可能重复写 body - 别在
recover里尝试重试或 fallback——panic 表示程序状态已不可信 - 如果用了第三方 router(如 Gin、Echo),它们自带 recover 中间件,自己再套一层会导致双 error 响应
性能敏感场景慎用 context.WithValue
中间件常用来往 context.Context 塞数据(如用户 ID、请求 ID),但 context.WithValue 是带锁的 map 操作,高频请求下有微小开销。更重要的是:它破坏类型安全,容易拼错 key 或类型断言失败。
更稳妥的做法是定义结构体 + context.WithValue 一次,或用 typed context key:
type ctxKey string
const userCtxKey ctxKey = "user"
func Auth() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := &User{ID: 123}
r = r.WithContext(context.WithValue(r.Context(), userCtxKey, u))
next.ServeHTTP(w, r)
})
}
}
- key 类型必须是 unexported(小写),否则不同包可能冲突
- 不要用
string当 key,比如context.WithValue(r.Context(), "user_id", 123)—— 一不小心就写成"userid" - 如果只是透传少量字段,考虑用自定义
*http.Request包装器,比 context 更快也更明确
next.ServeHTTP 的中间件、一个提前写 header 的日志器、一个 panic 后没 recover 的 handler——这些都不会报编译错误,但会在压测或上线后突然失效。










