Skip to content

gRPC Interceptors

Interceptors are the gRPC equivalent of HTTP middleware.

func authInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
md, _ := metadata.FromIncomingContext(ctx)
if len(md["token"]) == 0 {
return nil, status.Error(codes.Unauthenticated, "missing token")
}
return handler(ctx, req)
}
server := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
greeter.RegisterGreeterServer(grpcServer, srv)
})
server.AddUnaryInterceptors(authInterceptor)
server.Start()
conn, _ := zrpc.NewClient(c.GreeterRpc,
zrpc.WithUnaryClientInterceptor(func(ctx context.Context, method string,
req, reply any, cc *grpc.ClientConn,
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx = metadata.AppendToOutgoingContext(ctx, "token", getToken())
return invoker(ctx, method, req, reply, cc, opts...)
}),
)
InterceptorWhat it does
RecoverInterceptorConverts panics to gRPC errors
PrometheusInterceptorRecords RPC duration metrics
TracingInterceptorOpenTelemetry span creation
BreakerInterceptorCircuit-breaker protection
SheddingInterceptorLoad-shedding under heavy traffic
TimeoutInterceptorPer-RPC deadline enforcement