首页 > 解决方案 > gRPC go:在服务级别应用拦截器

问题描述

gRPC 拦截器通过ServerOption. 请参阅文档 如何在服务级别应用拦截器。例如,我可能只需要为受保护的服务应用身份验证器拦截器。这可能吗?

标签: grpcgrpc-go

解决方案


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


推荐阅读