Home > Net >  GRPC Service with Generic proto request data in GoLang
GRPC Service with Generic proto request data in GoLang

Time:03-07

I have 3 protos as follow:

1 - record.proto

message Record {
    int64 primaryKey = 1;     

    int64 createdAt = 2;
    int64 updatedAt = 3;
}

2 - user.proto

import "record.proto";
message User {
    Record record = 31;
    string name = 32;
    string email = 33;
    string password = 34;
}

3 - permissions.proto

import "record.proto";
    message Permissions{
        Record record = 31;
        string permission1= 32;
        string permission2= 33;
    }

Question1: Is there a way to implement a grpc server and client in golang that takes specifically Record as request but entertains both later types. i.e User and Permissions. Something like:

service DatabaseService {
    rpc Create(Record) returns (Response);
}

So that I can send grpc client request as both follow:

Create(User) returns (Response);
Create(Permissions) returns (Response);

CodePudding user response:

You can use oneof which allows the client to send either User or Permissions. Refer https://developers.google.com/protocol-buffers/docs/proto3#oneof

message Request {
    oneof request {
        User user = 1;
        Permissions permissions = 2;
    }
}

So client can fill any of them in the request.

service DatabaseService {
    rpc Create(Request) returns (Response);
}
  • Related