Go 语言通过函数式编程和 HTTP Handler 链式调用自然实现中间件,核心是闭包包装 handler,在 ServeHTTP 前后插入逻辑;支持日志、鉴权、CORS 等,并通过 context 安全传递请求数据。
Go 语言本身没有内置的“中间件”概念,但通过 函数式编程 + HTTP 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) }) }
中间件可逐层嵌套,形成处理链。推荐从外到内顺序注册(即先写的中间件最外层,最后执行):
示例组合方式:
handler := http.HandlerFunc(yourBusinessHandler)
handler = authMiddleware(handler) // 鉴权(需在 CORS 后?视需求而定)
handler = corsMiddleware(handler) // 跨域(通常放最外层或紧邻业务层)
handler = loggingMiddleware(handler) // 日志(建议最外层,覆盖全部)
http.ListenAndServe(":8080", handler)
避免用全局变量或修改 *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)
}
w.WriteHeader() 或写入 body,你不能再修改 header(会 panic)。可在 wrapper 中用 ResponseWriter 包装器拦截写操作(如 github.com/gorilla/handlers.CompressHandler 内部做法)github.com/gorilla/handlers 提供日志、CORS、压缩等开箱即用中间件