The UnaryClientInterceptor interface from google.golang.org/grpc has a signature like
type UnaryClientInterceptor func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
My understanding of this interface is that implementations are called before the request is made, allowing for the enrichment and modification of the request before it hits the network.
I don't, however, understand the reply parameter since the request hasn't been made yet. Am I misunderstanding the use of this interface or are there interesting things that can be done with the reply parameter even given that we can't actually access the response?
You can inspect the response within the
replyargument after the gRPC call is made.One of the arguments of the unary interceptor is the
invokerfunction, which has typeUnaryInvoker. Within the unary interceptor, you are supposed to call this function, as mentioned in the docs:And
invokeritself takesreqandreplyas arguments. You can call the invoker and then inspectreply.But, how to inspect it? The dynamic type of the
replyinterface is supposed to be a pointer to the return type of your gRPC handler as defined in your protobuffer schema. You can inspect the value ofmethodto know what return type to expect.To understand this better, you can take a look at the code generated by
protoc. The implementation of a gRPC method shows what are the actual arguments used to callInvoke.Let's say you have a protobuffer like:
The generated code for the
GetFoomethod will look like:Therefore you know the type of
replybased on the value ofmethod. From then, you can obtain the following example unary interceptor: