Go中过滤器链通过func(http.Handler) http.Handler实现包装式组合,必须显式调用next.ServeHTTP(w, r);责任链则用结构体封装HandlerNode接口,支持动态中断;中间件不应defer关闭DB连接,资源应绑定request context。
func(http.Handler) http.Handler 实现过滤器链Go 的 http.Handler 天然适合构建过滤器链,核心是「包装」而非继承。每个中间件接收一个 http.Handler,返回
一个新的 http.Handler,最终把请求一层层传下去。
常见错误是忘记调用 next.ServeHTTP(w, r),导致请求中断;或者在中间件里提前 w.WriteHeader() 后又试图写 body,触发 http: multiple response.WriteHeader calls 错误。
next.ServeHTTP(w, r) 才能继续链路http.ResponseWriter,但它是不可重置的,写完状态码和 header 就不能再改httptest.ResponseRecorder 或自定义 ResponseWriter 包装器func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("START %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r) // 必须调用
log.Printf("END %s %s", r.Method, r.URL.Path)
})
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return // 不调用 next,链路终止
}
next.ServeHTTP(w, r)
})
}
当需要动态控制链行为(比如根据路径跳过某环节、或记录执行耗时、或聚合多个错误),纯函数链不够灵活。这时用结构体封装链节点更可控,每个节点实现 Handle(*http.Request, http.ResponseWriter) (bool, error) 接口——返回 true 表示继续,false 表示中断。
注意:责任链和过滤器链语义不同。过滤器链默认“全走一遍”,责任链强调“谁处理谁负责”。Go 里没有内置责任链接口,需自行建模,避免和 http.Handler 混淆。
r.Context() 传递(如 context.WithValue(r.Context(), key, val))type HandlerNode interface {
Handle(w http.ResponseWriter, r *http.Request) (proceed bool, err error)
}
type Chain struct {
nodes []HandlerNode
}
func (c *Chain) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, node := range c.nodes {
proceed, err := node.Handle(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !proceed {
return
}
}
}
// 示例节点:只对 /admin 路径生效
type AdminOnly struct{}
func (a AdminOnly) Handle(w http.ResponseWriter, r *http.Request) (bool, error) {
if r.URL.Path != "/admin" {
return true, nil // 继续
}
if r.Header.Get("X-Admin-Token") != "secret" {
http.Error(w, "Forbidden", http.StatusForbidden)
return false, nil // 中断
}
return true, nil
}
net/http/pprof 和自定义中间件调试链执行顺序实际部署中,链太长或逻辑嵌套深时,很难确认哪一环出错或超时。直接打日志易被冲刷,用 pprof 可抓取完整调用栈,但需注意:pprof 默认只暴露给 localhost,生产环境要加访问控制;且中间件里启停 trace 会影响性能。
更轻量的做法是在每个中间件开头用 log.SetPrefix(fmt.Sprintf("[%s] ", nodeName)),或统一用 context.WithValue(r.Context(), "trace_id", uuid.New().String()) 做链路追踪 ID。
pprof 的 /debug/pprof/profile?seconds=30 会阻塞当前 goroutine 30 秒,别在中间件里直接调用runtime/pprof.StartCPUProfile,记得配对 StopCPUProfile,否则文件句柄泄漏go.opentelemetry.io/otel 替代手写 trace,但小项目没必要引入 SDKdefer 关闭数据库连接?因为 defer 在函数返回时才执行,而中间件函数很快返回,但 handler 可能还在跑(比如异步写日志、发消息)。此时连接可能已被 defer 关掉,后续操作 panic。
正确做法是把资源生命周期绑定到 request context:用 context.WithTimeout(r.Context(), time.Second*5) 控制 DB 查询超时,并在 handler 内部显式关闭连接(或用连接池,让 db.QueryRowContext 自动管理)。
sql.Open + 连接池,且不 defer close