1

How can I send metadata from grpc-gateway to grpc server?

On the client(grpc-gateway):

func (c *Client) MiddlewareAuth(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()

        ...

        ctxOut := metadata.NewOutgoingContext(ctx, metadata.New(map[string]string{
            "key":    "value",
        }))

        r = r.WithContext(ctxOut)

        h.ServeHTTP(w, r)
    })
}

On the server:

func (s *Server) List(ctx context.Context, request *pb.Request) (*pb.Response, error) {
    md, _ := metadata.FromIncomingContext(ctx)
    fmt.Println(md)

    return &pb.Response{
        Ok: true
    }, nil
}

aleksl0l
  • 11
  • 1
  • 4

2 Answers2

0

It's possible to map HTTP headers to gRPC metadata, as described here

This should work:

// in Client.MiddlewareAuth
r.Header.Set("Grpc-Metadata-My-Data", "...")

// in Server.List
md.Get("grpcgateway-My-Data")
torkel
  • 2,096
  • 3
  • 10
  • 20
0

You might not like the default mapping rule and might want to pass through all the HTTP headers, for example:

  1. Write a HeaderMatcherFunc.

  2. Register the function with WithIncomingHeaderMatcher

e.g.

func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-Custom-Header1":
 return key, true
 case "X-Custom-Header2":
 return "custom-header2", true
 default:
 return key, false
 }
}

mux := runtime.NewServeMux(
 runtime.WithIncomingHeaderMatcher(CustomMatcher),
)

To keep the the default mapping rule alongside with your own rules write:

func CustomMatcher(key string) (string, bool) {
 switch key {
 case "X-User-Id":
 return key, true
 default:
 return runtime.DefaultHeaderMatcher(key)
 }
}

It will work with both:

$ curl --header "x-user-id: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

and

$ curl --header "X-USER-ID: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...

To access this header on gRPC server side use:

userID := ""
if md, ok := metadata.FromIncomingContext(ctx); ok {
 if uID, ok := md["x-user-id"]; ok {
 userID = strings.Join(uID, ",")
 }
}

Also, you should check out the tutorial series on gRPC-Gateway, i.e., https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/.

Rajiv Singh
  • 2,947
  • 2
  • 11
  • 30