A simple example, there is a client calling any methods, on the server side, you need to implement a simple counter for the number of calls to these methods and, for example, transfer this counter to another client. because it has a signature:

`func UnaryServerInterceptor( ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, ) (interface{}, error) { reply, err := handler(ctx, req) return reply, err }` 

that is, from here it will not be possible to extract any data and further transfer it. Can you please tell me how in microservice architecture using golang + gRPC to implement this?

    1 answer 1

    The counter can be made through the interceptor, in the context to attach a value that will increase with each call and a new context to put into the handler, and already in the implemented method to retrieve this value.

    Example:

     // CounterUnaryServerInterseptor interseptor, который будет производить подсчет вызовов методов сервера func CounterUnaryServerInterseptor() grpc.UnaryServerInterceptor { methods := make(map[string]int64, 0) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { var count int64 var ok bool if count, ok = methods[info.FullMethod]; ok { count += 1 } methods[info.FullMethod] = count newCtx := context.WithValue(ctx, "count", count) return handler(newCtx, req) } } // MethodGRPCServer реализация метода в котором извлекается значение `count` func (s *Server) MethodGRPCServer(ctx context.Context, req *pb.Request) (*pb.Response, error) { countInterface := ctx.Value("count") count, ok := countInterface.(int64) if !ok { log.Printf("Can't cast to int64, data: %+v", countInterface) } log.Print(count) // Ваш код return response, nil } func main() { // Инициализация gRPC сервера grpcServer := grpc.NewServer( CounterUnaryServerInterseptor(), ) // Регистрация методов // ... } 
    • Tell me please, but what if I have server side streaming, and the method does not pass the context to the signature in the generated proto file? - Dmitry Milevsky