Go 语言通过函数式编程和 HTTP Handler 链式调用自然实现中间件,核心是闭包包装 handler,在 ServeHTTP 前后插入逻辑;支持日志、鉴权、CORS 等,并通过 context 安全传递请求数据。

Go 语言本身没有内置的“中间件”概念,但通过 函数式编程 + HTTP Handler 链式调用 可以非常自然、轻量地实现中间件机制,尤其适合请求预处理(如鉴权、跨域、参数校验)和日志记录等通用逻辑。
核心思路:用闭包包装 handler
Go 的 http.Handler 接口只有一个方法:ServeHTTP(http.ResponseWriter, *http.Request)。中间件本质就是——接收一个 handler,返回另一个 handler,并在其前后插入自定义逻辑。
典型写法:
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)
// ✅ 调用下游 handler(可能是下一个中间件,也可能是最终业务 handler)
next.ServeHTTP(w, r)
// ✅ 请求后:记录耗时、状态码
duration := time.Since(start)
log.Printf("END %s %s [%d] %.2fms", r.Method, r.URL.Path, w.Header().Get("Status"), float64(duration.Microseconds())/1000)
})
}
链式组合多个中间件
中间件可逐层嵌套,形成处理链。推荐从外到内顺序注册(即先写的中间件最外层,最后执行):
立即学习“go语言免费学习笔记(深入)”;
- 日志中间件 → 记录完整生命周期
- 跨域中间件(CORS)→ 设置响应头
- 身份验证中间件 → 检查 token 并注入用户信息到 context
- 最终业务 handler → 处理具体路由逻辑
示例组合方式:
handler := http.HandlerFunc(yourBusinessHandler)
handler = authMiddleware(handler) // 鉴权(需在 CORS 后?视需求而定)
handler = corsMiddleware(handler) // 跨域(通常放最外层或紧邻业务层)
handler = loggingMiddleware(handler) // 日志(建议最外层,覆盖全部)
http.ListenAndServe(":8080", handler)
在中间件中安全传递数据:使用 context
避免用全局变量或修改 *http.Request 字段。Go 推荐通过 r.Context() 注入请求级数据(如用户 ID、请求 ID、租户信息):
type ctxKey string
const userCtxKey ctxKey = "user"
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
userID, err := validateToken(token)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// ✅ 将用户信息注入 context
ctx := context.WithValue(r.Context(), userCtxKey, userID)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
// 在业务 handler 中读取:
func yourBusinessHandler(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value(userCtxKey).(string) // 类型断言需谨慎(建议封装工具函数)
fmt.Fprintf(w, "Hello, user %s", userID)
}
实用技巧与注意事项
- 不要忘记调用 next.ServeHTTP():遗漏会导致请求中断,无响应
-
响应头可能被提前写入:若下游 handler 已调用
w.WriteHeader()或写入 body,你不能再修改 header(会 panic)。可在 wrapper 中用ResponseWriter包装器拦截写操作(如github.com/gorilla/handlers.CompressHandler内部做法) - 错误处理要统一兜底:中间件内 panic 应 recover 并返回 500,避免整个服务崩溃
- 性能敏感场景慎用深度嵌套:每个中间件都是一次函数调用+闭包,但对绝大多数 Web 服务影响极小
-
可复用已有库:如
github.com/gorilla/handlers提供日志、CORS、压缩等开箱即用中间件










