如何使用Golang实现装饰器+代理模式_增强功能和访问控制

11次阅读

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

如何使用Golang实现装饰器+代理模式_增强功能和访问控制

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)(假设 processPaymentHandler[PayReq, PayResp]

text=ZqhQzanResources