Home > Mobile >  GRPC : How to pass value from interceptor to service function
GRPC : How to pass value from interceptor to service function

Time:02-15

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

unc 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.

CodePudding user response:

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"]

CodePudding user response:

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"]
  • Related