GRPC:如何从拦截器传递值给服务函数

huangapple go评论96阅读模式
英文:

GRPC : How to pass value from interceptor to service function

问题

我有一个一元拦截器,用于验证 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("--> 一元拦截器:%s", info.FullMethod)

		if info.FullMethod == "/AntmanServer.AntmanUserRoutes/LoginUser" {
			return handler(ctx, req)
		}

		userId, _, err := authorize(ctx)
		if err != nil {
			return fmt.Sprintf("错误:%s", err), err
		}

		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))

但都没有起作用,你想知道如何解决这个问题。提前感谢你的帮助。

英文:

I have a unary interceptor that validates the jwt token and parses the id and role. Now I need to pass these to the service function.

Interceptor

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)
}

}

I have this tried

newCtx := metadata.AppendToOutgoingContext(ctx,"id-key", string(userId), "role-key", roles)

and also this

newCtx := context.WithValue(ctx, "id-key", string(userId))

but none works, how to do this. Thanks in advance.

答案1

得分: 4

好的,以下是翻译好的内容:

好的,问题已经解决,感谢评论区的每个人。我将发布这个解决方案,供未来遇到类似问题的人参考。

// 拦截器
md, ok := metadata.FromIncomingContext(ctx)
if ok {
md.Append("id-key", string(id))
md.Append("role-key", role)
}
newCtx := metadata.NewIncomingContext(ctx, md)
return handler(newCtx, req)

// RPC 函数
md, ok := metadata.FromIncomingContext(ctx)
Userid := md["id-key"]
role := md["role-key"]

英文:

Ok, the problem is solved, thanks to everyone in the comments. I am posting this solution for people coming here in future.

	//interceptor
    md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		md.Append("id-key", string(id))
		md.Append("role-key", role)
	}
	newCtx := metadata.NewIncomingContext(ctx, md)
	return handler(newCtx, req)


   //Rpc function
   md, ok := metadata.FromIncomingContext(ctx)
   Userid := md["id-key"]
   role := md["role-key"]

答案2

得分: 1

在客户端中编写:

md := metadata.Pairs("key", "value")
ctx := metadata.NewOutgoingContext(context.Background(), md)

在服务器端中读取:

md, ok := metadata.FromIncomingContext(ctx)
value := md["key"]
英文:

Write in client:

md := metadata.Pairs("key", "value")
ctx := metadata.NewOutgoingContext(context.Background(), md)

And read in server:

md, ok := metadata.FromIncomingContext(ctx)
value := md["key"]

huangapple
  • 本文由 发表于 2022年2月14日 23:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/71114401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定