2

I'm trying to pass some information about how an RPC call is performed from the RPC function itself to the unary server interceptor. How can I achieve this?

The RPC server:

func (s *myServer) Get(ctx context.Context, in *MyRequest) (*MyResponse, error) {
   // Do some work, 
   // But also generate some metrics that should be made available to the server interceptor after the work here is done,
   // probably through context
   return &MyResponse{}, nil
}

And the unary server interceptor:

func (mi *metricsInterceptor) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
    return mi.doServerUnary
}

and

func (mi *metricsInterceptor) doServerUnary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (out interface{}, err error) {
   defer func() {
      // get those metrics generated in the call, probably from the context, and do stuff with them
   }
   out, err = handler(ctx, req)
}
svakili
  • 1,909
  • 4
  • 19
  • 24
  • you can do something similar to [grpc opentracing](https://github.com/grpc-ecosystem/go-grpc-middleware/blob/master/tracing/opentracing/server_interceptors.go#L24). Or you could just use grpc opentracing, which provides some useful interceptor middlewares – blackgreen Jun 20 '22 at 19:07
  • the idea is that the interceptor, before calling `handler(ctx, req)` creates some collector that is injected in the context. The handler implementation will then extract the collector from the context and save the metrics into it. Then *before returning from the interceptor*, you have the collector in scope, and can inspect it there. – blackgreen Jun 20 '22 at 19:11

0 Answers0