How to Add gRPC Interceptors (Middleware) in Go

Web
Add gRPC interceptors in Go by wrapping your server or client options with UnaryInterceptor or StreamInterceptor functions to handle cross-cutting concerns like logging and auth.

Add gRPC interceptors by wrapping your server or client options with grpc.UnaryServerInterceptor or grpc.StreamServerInterceptor functions.

func loggingInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
    log.Println("Request received")
    return handler(ctx, req)
}

server := grpc.NewServer(
    grpc.UnaryInterceptor(loggingInterceptor),
)

For streaming RPCs, use grpc.StreamInterceptor with a similar signature that wraps the grpc.StreamServer.