gRPC go:在服务级别应用拦截器

gRPC go: apply interceptor at service level

gRPC拦截器通过ServerOption应用到服务端。查看 doc 如何在服务级别应用拦截器。例如,我可能只需要为受保护的服务应用身份验证器拦截器。这可能吗?

gRPC Go 拦截器接收一个 StreamServerInfo (or a UnaryServerInfo) 参数,其中包含调用的服务和方法名称等。您可以使用它来过滤基于 service/method.

的拦截器行为

除了 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
}