如何在 Go 的 net/http 中为 HTTP 处理器添加中间件

17次阅读

如何在 Go 的 net/http 中为 HTTP 处理器添加中间件

本文详解如何将自定义中间件(如 accept 头校验)正确应用于 go 标准库的 `http.handler`,包括中间件链式注册方法、常见错误规避及 app engine 兼容实践。

go 的 net/http 包中,中间件本质是接收 http.Handler 并返回新 http.Handler 的函数。要为 productHandler 添加 Accept 中间件,关键在于理解类型转换与调用顺序:http.HandleFunc 仅接受 func(http.ResponseWriter, *http.Request) 类型,而中间件需操作 http.Handler 接口。因此,必须先将普通处理器函数包装为 http.HandlerFunc,再传入中间件。

✅ 正确用法:链式注册中间件

http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))

此处:

  • http.HandlerFunc(productHandler) 将函数转为满足 http.Handler 接口的值;
  • Accept(…) 接收该 Handler,返回一个增强版 Handler;
  • http.Handle() 注册最终处理链(而非 http.HandleFunc,因后者不支持中间件组合)。

? 完整可运行示例

package main  import (     "fmt"     "net/http" )  // Accept 中间件:强制请求头 Accept: application/json func Accept(next http.Handler) http.Handler {     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {         if r.Header.Get("Accept") != "application/json" {             http.Error(w, "Unsupported Accept header. Expected: application/json", http.StatusNotAcceptable)             return         }         next.ServeHTTP(w, r)     }) }  func productHandler(w http.ResponseWriter, r *http.Request) {     switch r.Method {     case "GET":         fmt.Fprint(w, `{"products": []}`)     default:         http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)     } }  func main() {     // ✅ 正确:使用 http.Handle + 中间件包装     http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))      // 可扩展:多层中间件(如日志 + 认证 + Accept)     // http.Handle("/products/", Auth(Log(Accept(http.HandlerFunc(productHandler))))))      fmt.Println("Server starting on :8080...")     http.ListenAndServe(":8080", nil) }

⚠️ 常见错误分析

  • ❌ 错误写法:http.HandleFunc(“/products/”, Accept(…))
    → Accept 返回 http.Handler,但 HandleFunc 要求 func 类型,编译失败。

  • ❌ 自定义结构体 Pr 实现 ServeHTTP 时拼写错误(如 ServeHttp 少了大写 H)且未实现接口方法签名,导致无法满足 http.Handler 接口。

  • ❌ 中间件内部遗漏 next.ServeHTTP(w, r) 调用,或位置错误(如放在 return 后),导致后续处理器永不执行。

? 在 google App Engine SDK 中的注意事项

App Engine 标准环境(Go 1.11+)完全兼容标准 net/http,上述方案可直接使用。只需确保:

  • 主入口函数(如 init() 或 main())中完成路由注册;
  • 不依赖 http.ListenAndServe(App Engine 会自动注入 http.Handler 到运行时);
  • 若使用 app.yaml,保持 handlers 配置指向正确路径(如 /products/)。

✅ 总结

中间件不是“附加”到处理器上的装饰器,而是通过函数组合构建新处理器的过程。核心原则是:

  1. 所有中间件函数签名应为 func(http.Handler) http.Handler;
  2. 使用 http.HandlerFunc 显式转换普通函数;
  3. 用 http.Handle(而非 HandleFunc)注册中间件链;
  4. 确保中间件内 next.ServeHTTP 被正确调用且无逻辑阻断。

遵循此模式,即可轻松为任意处理器添加认证、日志、CORS、内容协商等通用能力。

text=ZqhQzanResources