Home > database >  Get request details from GRPC
Get request details from GRPC

Time:10-18

For normal HTTP requests, I can get details like the protocol, remote IP, host, method, request URL, referrer, user agent, etc. I know I can extract metadata associated with the request by doing this:

var extracted string

meta, ok := metadata.FromIncomingContext(ctx)
if ok {
    if value, ok := meta[header]; ok && len(value) > 0 {
         extracted = value[0]
    }
}

Furthermore, I understand that HTTP headers will be inserted into the metadata, but that only applies for requests made via the HTTP gateway so requests made from a GRPC client wouldn't necessarily include this information.

But I'm not sure which values to use for header or if this information would be available in the metadata at all, or if I should check somewhere else. How can I get this request-related information from a GRPC request?

CodePudding user response:

Per doc Metadata, in order to read the head from the metadata through Get after metadata.FromIncomingContext. And since the MD is type MD map[string][]string you could try to iterate the map MD and treat it as same as Headers of HTTP request.

Note: all the keys will be automatically converted to lowercase

Doc gRPC over http2

Request-Headers are delivered as HTTP2 headers in HEADERS CONTINUATION frames.

Request-Headers → Call-Definition *Custom-Metadata

HTTP2 requires that reserved headers, ones starting with ":" appear before all other headers. Additionally implementations should send Timeout immediately after the reserved headers and they should send the Call-Definition headers before sending Custom-Metadata.

Sample codes

import "google.golang.org/grpc/metadata"

func (s Server) Method(ctx context.Context, *Request) (*Response, error) {
  var values []string

  md, ok := metadata.FromIncomingContext(ctx)
  for key, val := range md {
     // get key and val of headers
  }
  
}
  • Related