gRPC Unary Interceptor Chain
Source: Custom
Topics: gRPC, interceptors, middleware composition
Problem
gRPC only lets you register one unary server interceptor. Real services need many (auth,
logging, metrics, recovery, rate limiting), so you compose them into a single chained interceptor —
the gRPC equivalent of the HTTP middleware-chain challenge.
Requirements:
ChainUnary(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor
- The returned interceptor runs the supplied interceptors in order: the first wraps the
second, … the last wraps the real handler. (Same nesting as HTTP middleware: first in, last out.)
- Each interceptor receives a
handler that invokes the rest of the chain, so any interceptor
may short-circuit by returning before calling handler.
func ChainUnary(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor
Note: this challenge depends on google.golang.org/grpc for the interceptor type signatures
(UnaryServerInterceptor, UnaryServerInfo, UnaryHandler). The tests exercise the chain
directly with a fake handler — no network, no .proto, no codegen.
Key concepts
grpc.UnaryServerInterceptor: func(ctx, req, info, handler) (resp, err) — it gets the
request and a handler it must call to continue. Returning without calling handler
short-circuits (e.g. an auth failure).
- Recursive chaining: build a
handler for index i that calls interceptors[i] with a
handler that recurses to i+1; the base case (past the last interceptor) calls the real
handler. This is exactly how grpc-go's ChainUnaryInterceptor works internally.
- Order = nesting:
ChainUnary(a, b) runs a-pre → b-pre → handler → b-post → a-post. The
first interceptor is outermost, so it sees the request first and the response last.
Run
go test -v ./challenges/networking/grpc-interceptor/
Sign in to submit your solution.