Golang gRPC Context

When we need to pass metadata between services the gRPC metadata package can be used pass key-value pairs in the context.

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

We can add key-value pairs of metadata to the request context:

func main() {
  // gRPC client and connection
  // ...

  // new request context
  ctx := context.Background()

  // add key-value pairs of metadata to context
  ctx = metadata.NewContext(
    ctx,
    metadata.Pairs("key1", "val1", "key2", "val2"),
  )

  // send request w/ context
  reply, err := client.Say(ctx, &pb.Greeting{
    Message: "Yoo dawg!",
  })

  // ...
}

Then when the request lands on the downstream service we can parse out the key-value pairs from the request context:

type demoServer struct {}

func (s *demoServer) Say(
  ctx context.Context,
  greeting *pb.Greeting,
) (*pb.Reply, error) {
  md, _ := metadata.FromContext(ctx)
  // context data
  // md["key1"] = "val1"
  // md["key2"] = "val2"
  // ...
}

func main() {
  s := new(demoServer)
  grpcServer := grpc.NewServer()
  pb.RegisterDemoServer(grpcServer, s)
  grpcServer.Serve(ln)
}

Hi, I'm Harlow. I head up the enginnering team at Clearbit. I've been writing software professionally for the better part of a decade for companies like Bills.com, thoughtbot, and HotelTonight. I like fast APIs, streaming event data, and of course my lovely @tayloresque.