Sobes.tech
Senior

Is there no middleware in gRPC API?

sobes.tech AI

Answer from AI

gRPC does not have a built-in concept of middleware like HTTP frameworks, but similar functionality can be implemented using interceptors.

Interceptors are functions that intercept RPC calls before or after processing, allowing you to add logic such as authentication, logging, metrics, or error handling.

In Go gRPC, there are two types of interceptors:

  • Unary Interceptor — for unary RPC calls (one request, one response)
  • Stream Interceptor — for streaming calls

Example of a unary interceptor:

func loggingInterceptor(
    ctx context.Context,
    req interface{},
    info *grpc.UnaryServerInfo,
    handler grpc.UnaryHandler,
) (interface{}, error) {
    log.Printf("RPC call: %s", info.FullMethod)
    resp, err := handler(ctx, req)
    return resp, err
}

// When registering the server
server := grpc.NewServer(grpc.UnaryInterceptor(loggingInterceptor))

Thus, although there is no middleware as such, interceptors perform a similar role.