You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package interceptor
|
|
|
|
import (
|
|
ctxpkg "github.com/noahlann/nnet/pkg/context"
|
|
interceptorpkg "github.com/noahlann/nnet/pkg/interceptor"
|
|
)
|
|
|
|
// chain 拦截器链实现
|
|
type chain struct {
|
|
interceptors []interceptorpkg.Interceptor
|
|
index int
|
|
}
|
|
|
|
// NewChain 创建拦截器链
|
|
func NewChain(interceptors ...interceptorpkg.Interceptor) interceptorpkg.Chain {
|
|
return &chain{
|
|
interceptors: interceptors,
|
|
index: 0,
|
|
}
|
|
}
|
|
|
|
// Next 执行下一个拦截器
|
|
func (c *chain) Next(data []byte, ctx ctxpkg.Context) ([]byte, bool, error) {
|
|
if c.index >= len(c.interceptors) {
|
|
// 所有拦截器都执行完毕,返回原始数据
|
|
return data, true, nil
|
|
}
|
|
|
|
interceptor := c.interceptors[c.index]
|
|
c.index++
|
|
|
|
// 创建新的链用于递归调用
|
|
nextChain := &chain{
|
|
interceptors: c.interceptors,
|
|
index: c.index,
|
|
}
|
|
|
|
return interceptor.Intercept(data, ctx, nextChain)
|
|
}
|
|
|
|
// Execute 执行拦截器链
|
|
func Execute(data []byte, ctx ctxpkg.Context, interceptors ...interceptorpkg.Interceptor) ([]byte, bool, error) {
|
|
chain := NewChain(interceptors...)
|
|
return chain.Next(data, ctx)
|
|
}
|
|
|