1

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

4

2 回答 2

2

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

于 2020-02-06T08:23:26.013 回答
0

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

于 2020-02-06T08:05:59.583 回答