How to Handle gRPC Metadata (Headers) in Go

Web
Handle gRPC metadata in Go by retrieving it from the request context using metadata.FromIncomingContext or attaching it with metadata.AppendToOutgoingContext.

You handle gRPC metadata in Go by accessing the metadata.MD map stored in the request context. Use metadata.FromIncomingContext to retrieve headers on the server side or metadata.AppendToOutgoingContext to attach them on the client side.

import (
	"context"
	"google.golang.org/grpc/metadata"
)

// Server-side: Read metadata
func (s *Server) Handle(ctx context.Context, req *Request) (*Response, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, fmt.Errorf("no metadata found")
	}
	// Access header: md.Get("key") returns []string
	val := md.Get("x-custom-header")
	return &Response{}, nil
}

// Client-side: Send metadata
ctx := metadata.AppendToOutgoingContext(context.Background(), "x-custom-header", "value")
resp, err := client.Call(ctx, &Request{})