Documentation
¶
Overview ¶
Package aop 提供轻量级方法级切面(面向切面编程),对标 Spring AOP 的 @Before / @After / @Around,用于 Service 层:
- 方法调用前后拦截(日志、耗时统计)
- 前置校验(权限、参数),返回 error 终止调用
- 环绕包装(事务、重试、熔断、上下文注入)
Web 层请使用 webiris 中间件(等同环绕切面:AccessLog/Auth/Limit/ErrorHandler)。 本包面向非 Web 场景(Service/Repository 方法)。
用法:
// 原始方法(任意签名)
getUser := func(ctx context.Context, id int64) (*User, error) { ... }
// 环绕切面:耗时 + 日志
getUser = aop.Around(getUser, func(ctx context.Context, params []interface{},
next func() ([]interface{}, error)) ([]interface{}, error) {
start := time.Now()
results, err := next()
log.Printf("GetUser cost=%s err=%v", time.Since(start), err)
return results, err
}).(func(context.Context, int64) (*User, error))
// 前置校验:返回 error 终止调用
getUser = aop.Before(getUser, func(ctx context.Context, params []interface{}) error {
if id := params[1].(int64); id <= 0 {
return errors.New("invalid user id")
}
return nil
}).(func(context.Context, int64) (*User, error))
与 simpleioc 配合:将装饰后的 Service 结构注册进容器, 业务调用方无感知(接口签名不变)。
Index ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrAborted = errors.New("aop: call aborted by before hook")
ErrAborted 由前置切面返回时,调用被终止的通用错误。
Functions ¶
func After ¶
func After(fn interface{}, hooks ...AfterHook) interface{}
After 为目标函数附加后置切面(记录日志/耗时/结果审计)。
func Around ¶
func Around(fn interface{}, hook AroundHook) interface{}
Around 为目标函数附加环绕切面(事务/重试/熔断/耗时统计)。
func Before ¶
func Before(fn interface{}, hooks ...BeforeHook) interface{}
Before 为目标函数附加前置切面,返回与原函数同签名的新函数(需类型断言使用)。 hook 返回 error 时终止调用,直接返回该错误(结果切片为空)。
Types ¶
type AroundHook ¶
type AroundHook func(ctx context.Context, params []interface{}, next func() ([]interface{}, error)) ([]interface{}, error)
AroundHook 环绕切面:包裹目标方法调用;调用 next() 执行目标方法。
type BeforeHook ¶
BeforeHook 前置切面:在目标方法调用前执行;返回 error 终止调用。
Click to show internal directories.
Click to hide internal directories.