Golang - grpc interceptor 问题
看了下 grpc 遇到一个问题,就是server的多拦截器问题,这里的拦截器可以理解成hook或者middleware,grpc 明确指出只支持一个。
This is intentional. We only provide a hook so that various complex interceptor patterns (e.g., chaining, nested, stack, concurrent, etc.) can be built on top of it without running into the argument of the execution ordering of the multiple interceptors while keeping grpc itself simple.
上面其实说,grpc 故意设计的这样,只能放一个钩子,这一个钩子来创建一些复杂的模式,防止了开发人员将过多的精力放到,函数调用链的执行顺序上。
假如有两个拦截器:
func composeUnaryServerInterceptors(interceptor, next grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
return interceptor(ctx, req, info,
func(nextCtx context.Context, nextReq interface{}) (interface{}, error) {
return next(nextCtx, nextReq, info, handler)
})
}
}
GitHub issue :
Interceptors aren't (easily) composable
我目前采用了问题描述中的推荐方式。
查看