grpc - gRPC go:在服务级别应用拦截器
问题描述
gRPC 拦截器通过ServerOption
. 请参阅文档
如何在服务级别应用拦截器。例如,我可能只需要为受保护的服务应用身份验证器拦截器。这可能吗?
解决方案
除了 eric 之前的回答之外,您还可以执行以下操作:
type key int
const (
sessionIDKey key = iota
)
var (
needTobeAllocate = [1]string{"allocate"}
)
func run() {
// server option
opts := []grpc.ServerOption{}
opts = append(opts, grpc.UnaryInterceptor(unaryInterceptor))
}
func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if checkAllocate(info.FullMethod) {
ctx = context.WithValue(ctx, sessionIDKey, "testsession")
}
return handler(ctx, req)
}
func checkAllocate(method string) bool {
for _, v := range needTobeAllocate {
if strings.Contains(strings.ToLower(method), v) {
return true
}
}
return false
}
推荐阅读
- android - 在 viewpager2 中禁用动画
- django - 使用用户以外的模型授权客户端
- sql - 如何从 oracle 获得最接近的值
- r - R - 在几个动作上运行一个循环
- javascript - 使用JS将鼠标悬停在文本上时更改正文背景图像
- vaadin - TemplateRenderer 返回 null (Vaadin Flow / 14.1)
- java - java.lang.IllegalStateException:没有在 xxxxx(位置地址)错误上设置 NavController
- c - 左移给了我奇怪的结果
- c# - 我怎样才能把这个简单的方法变成一个通用的方法?
- java - 使用套接字和 Ajax 的客户端-服务器-客户端通信 - Java