0Pricing
Go Academy · Lesson

gRPC Interceptors and Metadata

Auth, logging middleware and gRPC metadata

gRPC Interceptors and Metadata is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What are interceptors?

gRPC interceptors (middleware) run before or after RPC handlers. They add cross-cutting concerns: logging, auth token validation, metrics, panic recovery, and tracing.

Unary server interceptor

A unary server interceptor wraps the handler with additional logic:

func LoggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    log.Printf("RPC: %s", info.FullMethod)
    resp, err := handler(ctx, req)
    log.Printf("done: %v", err)
    return resp, err
}

grpcSrv := grpc.NewServer(grpc.UnaryInterceptor(LoggingInterceptor))

Stream server interceptor

Similar to unary but wraps the stream handler:

func StreamLogging(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
    log.Printf("stream: %s", info.FullMethod)
    return handler(srv, ss)
}

Chaining interceptors

Use grpc.ChainUnaryInterceptor (Go gRPC v1.38+) to apply multiple interceptors in order:

grpcSrv := grpc.NewServer(
    grpc.ChainUnaryInterceptor(LoggingInterceptor, AuthInterceptor, MetricsInterceptor),
)

Client interceptors

Client-side unary interceptors wrap outgoing calls — useful for injecting auth tokens, retries, or tracing headers:

conn, _ := grpc.NewClient(addr,
    grpc.WithUnaryInterceptor(ClientAuthInterceptor),
    grpc.WithTransportCredentials(insecure.NewCredentials()),
)

gRPC metadata

Metadata is key-value pairs sent alongside an RPC, analogous to HTTP headers. Use metadata.New and metadata.NewOutgoingContext on the client.

md := metadata.New(map[string]string{"authorization": "Bearer " + token})
ctx := metadata.NewOutgoingContext(context.Background(), md)

Reading metadata on server

Extract incoming metadata with metadata.FromIncomingContext:

md, ok := metadata.FromIncomingContext(ctx)
if !ok { return nil, status.Error(codes.Unauthenticated, "no metadata") }
token := md["authorization"]

Sending metadata from server

Send response headers and trailers from the server with grpc.SetHeader and grpc.SetTrailer:

grpc.SetHeader(ctx, metadata.Pairs("x-request-id", requestID))

go-grpc-middleware

The github.com/grpc-ecosystem/go-grpc-middleware/v2 library provides ready-made interceptors: recovery, logging (zap/logrus), auth, and more.

Auth interceptor pattern

Extract and validate a token in an interceptor; attach the user to the context for downstream handlers:

func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    md, _ := metadata.FromIncomingContext(ctx)
    if !validateToken(md["authorization"]) {
        return nil, status.Error(codes.Unauthenticated, "invalid token")
    }
    return handler(ctx, req)
}

Panic recovery interceptor

Wrap handlers to recover from panics and return an Internal error instead of crashing:

defer func() {
    if r := recover(); r != nil {
        err = status.Errorf(codes.Internal, "panic: %v", r)
    }
}()

Quick Check

How do you pass authentication tokens between a gRPC client and server?

Recap: gRPC Interceptors and Metadata

Key points:

  • Unary interceptor: func(ctx, req, info, handler) (resp, error)
  • grpc.ChainUnaryInterceptor for multiple interceptors
  • Metadata is key-value pairs; analogous to HTTP headers
  • Auth interceptor: extract metadata → validate → add user to context

Frequently asked questions

Is the “gRPC Interceptors and Metadata” lesson free?

Yes — the full text of “gRPC Interceptors and Metadata” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “gRPC Interceptors and Metadata”?

Auth, logging middleware and gRPC metadata You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “gRPC Interceptors and Metadata” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Protocol Buffers and .proto Files
  2. Implementing a Unary gRPC Service
  3. Server and Client Streaming
  4. gRPC Interceptors and Metadata
← Back to Go Academy