how to retrieve metadata set in filter in go-grpc

269 Views Asked by At

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?

0

There are 0 best solutions below