【发布时间】:2022-12-03 16:28:47
【问题描述】:
我有一个验证 jwt 令牌并解析 id 和角色的一元拦截器。现在我需要将这些传递给服务功能。
拦截器
func Unary() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
log.Printf("--> unary interceptor: %s ", info.FullMethod)
if info.FullMethod == "/AntmanServer.AntmanUserRoutes/LoginUser" {
return handler(ctx, req)
}
userId, _, err := authorize(ctx)
if err != nil {
return fmt.Sprintf("Error : %s", err), err
}
//newCtx := metadata.AppendToOutgoingContext(ctx,"id-key", string(userId), "role-key", roles)
//header := metadata.Pairs("id-key", string(userId), "role-key", roles)
//grpc.SendHeader(ctx, header)
newCtx := context.WithValue(ctx, "id-key", string(userId))
return handler(newCtx, req)
}
}
我试过了
newCtx := metadata.AppendToOutgoingContext(ctx,"id-key", string(userId), "role-key", roles)
还有这个
newCtx := context.WithValue(ctx, "id-key", string(userId))
但没有一个工作,如何做到这一点。提前致谢。
【问题讨论】:
-
你所做的原则上是正确的。请澄清什么是“没有作品" 表示并显示您用来获取服务功能值的代码