0

When set grpc filter

func GetChainUnaryServerInterceptor() grpc.UnaryServerInterceptor {
    return grpc_middleware.ChainUnaryServer(
        grpc_auth.UnaryServerInterceptor(auth.CookieAuth),
        parseSessionToUidFilter,
    )
}

func parseSessionToUidFilter(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
    ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("uid", "123"))
    return handler(ctx, req)
}

In server, echo()

func (s *server) Echo(ctx context.Context, req *pb.EchoRequest) (resp *pb.EchoReply, err error) {
    md, _ := metadata.FromIncomingContext(ctx)
    fmt.Println(md)
    u := md.Get("uid")[0]
    username := u
    if username == "" {
        username = "whoever you are"
    }
    return &pb.EchoReply{Echo: "Hello, " + username}, nil
}

ctx detail in debug mode As you can see, uid is not with grpc-... above. Now I figured it out, I should use NewIncomingContext() in filter.

But how to set uid with mdIncomingKey above, with the pattern grpcgateway-*, e.g. grpcgateway-uid, do I have to rewrite the incomingHeaderMatcher function when boot my grpc-gateway?

jay cole
  • 1
  • 1
  • Please don't include images in questions particularly when the image represents easily copyable text. Images prevent us from grabbing text from them to help answer your question and images may not outlive the question. – DazWilkin Feb 09 '23 at 22:52
  • Please include a minimally-reproducible example of your interceptor. After [`AppendToOutgoingContext`](https://pkg.go.dev/google.golang.org/grpc/metadata#AppendToOutgoingContext), you will have a new `context.Context` (including the `uid`) that you should then use when you invoke the `handler`. – DazWilkin Feb 09 '23 at 22:53
  • sorry, I will edit it. And thank you for you reply, but I dont know where to set handler, I only used filter in my code – jay cole Feb 10 '23 at 13:42
  • Thank you for making the updates! Where are you registering the interceptor? When you [`grpc.NewServer(opts...)`](https://pkg.go.dev/google.golang.org/grpc#NewServer) are you adding the interceptor to the `opts`? ``opts := []grpc.ServerOption{grpc.ChainUnaryInterceptor(interceptors...)}`? – DazWilkin Feb 10 '23 at 17:48
  • It's a good idea to propagate the incoming metadata in the Interceptor too. You're currently discarding it. This won't affect your observed behavior. `if md, ok := metadata.FromIncomingContext(ctx); ok { ctx = metadata.NewOutgoingContext(ctx, md) }` – DazWilkin Feb 10 '23 at 17:50
  • Yes, I've registered interceptor in `grpc.NewServer(opts...)`. But I find maybe store uid using `context.WithValue` is more convenient. Since `FromIncomingContext` can only grab current ctx's metadata, and stop looking up to parents ctx's metadata, if I used `NewIncomingContext` in interceptor to propagate uid, then in business code, uid is the only thing in md. – jay cole Feb 11 '23 at 01:08

0 Answers0