Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unmarshall request in gRPC interceptor

In order to perform Authorization, some attributes from the request is to be read so that input for Authorization Server can be made

For example, this is the interceptor. Here prepareAuthZInput is called to preparing the input

func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
     input := prepareAuthZInput(info.FullMethod, req)
}

In this function, there's a big if-else part which checks for the actual type for the request, type casts it and then performs the input preparation.

func prepareAuthZInput(method string, req interface{}) {
   var input Input
   if methodName = "/Data/Call" {
       callRequest, ok := req.(CallRequest)
       if ok {
          // prepare input from callRequest
       }
   } else if methodName = "/Data/Receive" {
       receiveRequest, ok := req.(ReceiveRequest)
       if ok {
          // prepare input from receiveRequest
       }

   }
   return input
}

How can I improve this code?

like image 978
Pallav Jha Avatar asked Sep 06 '25 22:09

Pallav Jha


1 Answers

When doing something like this, it's typical to add auth data to the metadata instead of the request messages. This way the server doesn't need to inspect all the possible request payload types.

If you must use the request payload, it would be more idiomatic to use a type switch instead:

switch r := req.(type) {
  case CallRequest: // r is a CallRequest...
  case ReceiveRequest: // r is a ReceiveRequest...
  default:
    return status.Errorf(codes.Unimplemented, "unknown request type: %T", req)
}
like image 168
Doug Fawley Avatar answered Sep 08 '25 10:09

Doug Fawley