Go 语言虽无语法级装饰器,但可通过高阶函数模拟中间件(如日志、鉴权)、结构体+接口实现代理模式,并结合 context 与泛型提升复用性与类型安全。

Go 语言本身不支持 Python 那样的语法级装饰器(如 @decorator),但可以通过高阶函数、接口抽象和组合方式,自然地模拟“装饰器 + 代理模式”的行为——既能增强功能(如日志、重试、熔断),又能控制访问(如权限校验、限流、鉴权)。关键在于:用函数包装函数,用结构体包装接口,让增强逻辑与业务逻辑解耦。
用高阶函数实现装饰器风格的中间件
将核心逻辑抽象为函数类型(如 func(context.Context, Request) Response),再编写接受该函数并返回新函数的“装饰器”:
- 定义统一处理签名:
type HandlerFunc func(ctx context.Context, req interface{}) (interface{}, error) - 写日志装饰器:
func WithLogging(next HandlerFunc) HandlerFunc {
return func(ctx context.Context, req interface{}) (interface{}, error) {
log.Printf("→ %T received", req)
res, err := next(ctx, req)
log.Printf("← completed with error: %v", err)
return res, err
}
} - 链式组合:
handler := WithLogging(WithAuth(WithRateLimit(myBusinessHandler)))
执行时从外到内(装饰器)→ 内到外(返回)
用结构体+接口实现代理模式(静态代理)
当需要更精细控制(如字段级拦截、动态行为切换)时,定义接口 + 真实实现 + 代理结构体:
- 定义服务接口:
type UserService interface { GetUser(id int) (*User, error); CreateUser(u *User) error } - 真实实现:
type RealUserService struct{}实现全部方法 - 代理结构体持有一个
UserService字段:type UserProxy struct { svc UserService; authChecker AuthChecker }
在GetUser中先调authChecker.Check("read:user"),通过才委托给svc.GetUser - 优势:可嵌套代理(如
LoggingProxy{UserProxy{RealUserService{}}}),也便于单元测试(注入 mock svc)
结合 context 实现运行时访问控制
装饰器或代理中常需获取请求上下文信息(如用户身份、租户 ID、API Key)。推荐将认证信息注入 context.Context,而非靠参数传递:
立即学习“go语言免费学习笔记(深入)”;
- 中间层解析 token 后:
ctx = context.WithValue(ctx, userCtxKey, &User{ID: 123, Role: "admin"}) - 后续装饰器或代理直接从 ctx 取:
user, ok := ctx.Value(userCtxKey).(*User) - 权限检查示例:
if !user.Can("delete:user") { return nil, errors.New("forbidden") } - 注意:避免滥用
context.WithValue;建议定义强类型 key(type userCtxKey struct{})防止 key 冲突
进阶:用泛型简化通用装饰器(Go 1.18+)
避免为每种 handler 类型重复写装饰器。利用泛型统一抽象:
- 定义泛型处理器:
type Handler[T any, R any] func(context.Context, T) (R, error) - 泛型日志装饰器:
func LogHandler[T, R any](next Handler[T, R]) Handler[T, R] {
return func(ctx context.Context, req T) (R, error) {
log.Printf("handling %T", req)
return next(ctx, req)
}
} - 调用时自动推导:
h := LogHandler(processPayment)(假设processPayment是Handler[PayReq, PayResp])










