1
votes

I am trying to create REST endpoints for an existing gRPC service using grpc-gateway. The gRPC service makes use of "metadata" passed in grpc calls to authenticate. How do I set the metadata in my REST calls?

I have tried passing metadata key value pairs in the headers. But it did not set the metadata in context.

1
What library are you using to create and send out the REST reqs?Noah Eisen

1 Answers

4
votes

The trick here is using a custom incoming header matcher. You can see in the source code or grpc-gatway, that there is a WithIncomingHeaderMatcher that transforms incoming HTTP headers into metadata passed into the context (used later on by gRPC server handlers). By default it supports a set of so-called permanent HTTP headers which are passed as they are (so eg. Authorization header will come up as Authorization in the context), or you need to prefix your custom headers with a specific prefix, Grpc-Metadata-, see its usage here. In this case, Grpc-Metadata-Your-Name HTTP header will come up as Your-Name field in the metadata.

Again, if this is too problematic for you and you with to be able to pass eg. X-User-Id or any custom formatted headers into your app, you need to set up a custom header matcher. I would recommend to handle your headers explicitly and then fallback onto the default one (works great if you then update your dependencies and some new permanentHTTPHeader is added:

    func headerMatcher(header string) (string, bool) {
        if header == "X-User-Id" {
            return "x-user-id", true
        }
        return runtime.DefaultHeaderMatcher(header)
    }

Hope this helps!