Go中装饰者模式通过函数值、接口和高阶函数实现,典型应用是func(http.Handler) http.Handler中间件;也可用于通用函数装饰和结构体组合增强,关键在显式委托与层级合理选择。

Go 语言没有类和继承,也不支持方法重载或注解式装饰(如 Python 的 @decorator),所以“装饰者模式”在 Go 中不是靠语法糖实现的,而是通过函数值、接口和高阶函数组合来达成——本质是「把函数当参数传给另一个函数,返回增强后的新函数」。
用 func(http.Handler) http.Handler 实现 HTTP 中间件(最典型装饰者)
这是 Go 中最成熟、最常用的装饰者实践。每个中间件接收一个 http.Handler,返回一个新的 http.Handler,在调用原 handler 前后插入逻辑。
常见错误:忘记调用 next.ServeHTTP(w, r),导致请求链中断;或在调用前 panic 未 recover,导致整个服务崩溃。
- 中间件必须返回符合
http.Handler接口的值(通常用http.HandlerFunc匿名封装) - 多个中间件嵌套时,外层装饰内层,顺序敏感:最外层中间件最先执行,但最后结束
- 不要在中间件里修改
*http.Request的公开字段(如r.URL.Path),应使用r.WithContext()携带数据
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)
})
}
// 组合:log → auth → final handler
mux := http.NewServeMux()
mux.HandleFunc("/api/data", dataHandler)
http.ListenAndServe(":8080", loggingMiddleware(authMiddleware(mux)))
用函数类型定义通用装饰器(非 HTTP 场景)
当你想给任意函数加日志、重试、超时等能力时,需先定义统一的函数签名,再写对应装饰器。Go 不支持泛型函数装饰(Go 1.18+ 泛型可缓解,但仍有局限),所以常按用途分组定义。
立即学习“go语言免费学习笔记(深入)”;
容易踩的坑:闭包捕获变量导致所有装饰实例共享同一份状态;或装饰器内部 panic 后未处理,破坏调用方错误流。
- 推荐为每类业务函数定义专用类型别名,例如:
type ProcessFunc func(string) (string, error) - 装饰器函数应接收原函数 + 配置参数(如重试次数、超时时间),返回新函数
- 避免在装饰器内部启动 goroutine 后不等待完成,否则可能丢失结果或引发竞态
type ProcessFunc func(string) (string, error)func withRetry(f ProcessFunc, maxRetries int) ProcessFunc { return func(input string) (string, error) { var lastErr error for i := 0; i <= maxRetries; i++ { result, err := f(input) if err == nil { return result, nil } lastErr = err if i < maxRetries { time.Sleep(time.Second * time.Duration(i+1)) } } return "", lastErr } }
process := func(s string) (string, error) { if s == "fail" { return "", errors.New("simulated failure") } return "ok:" + s, nil }
robustProcess := withRetry(process, 2) result, err := robustProcess("fail") // 会重试 2 次
用接口 + 匿名字段模拟“装饰对象”(结构体增强)
当需要装饰的是某个结构体行为(比如给 FileReader 加缓存或解密能力),可用组合代替继承:定义接口,让装饰器结构体持有原对象并实现相同接口。
关键点:装饰器结构体必须显式实现全部接口方法,不能只嵌入原字段就认为自动实现了——Go 不支持自动委托。
- 装饰器结构体字段名建议用小写(如
reader io.Reader),避免外部直接访问被装饰对象 - 若原对象有指针方法,装饰器中调用时注意是否传了地址(
r.reader.Read(...)vs(&r.reader).Read(...)) - 避免循环装饰:A 装饰 B,B 又试图装饰 A,会导致无限递归或编译失败
type Reader interface {
Read(p []byte) (n int, err error)
}
type CachingReader struct {
reader io.Reader
cache []byte
}
func (cr *CachingReader) Read(p []byte) (int, error) {
if len(cr.cache) > 0 {
n := copy(p, cr.cache)
cr.cache = cr.cache[n:]
return n, nil
}
return cr.reader.Read(p) // 委托给底层 reader
}
// 使用
f, _ := os.Open("data.txt")
cached := &CachingReader{reader: f}
io.Copy(os.Stdout, cached)
真正难的不是写出一个装饰器,而是决定在哪一层做组合:HTTP handler 链?业务函数链?还是结构体嵌套?选错层级会让错误处理、上下文传递、可观测性变得异常脆弱。尤其当多个装饰器都依赖 context 或需要共享状态时,别硬塞进闭包,优先考虑用 struct 字段 + interface 显式管理生命周期。










