英文:
GRPC Service with Generic proto request data in GoLang
问题
我有3个proto文件,如下所示:
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;
}
问题1:
有没有办法在golang中实现一个grpc服务器和客户端,它接受Record作为请求,但同时也接受后面的两种类型,即User和Permissions。
类似这样:
service DatabaseService {
rpc Create(Record) returns (Response);
}
这样我就可以发送grpc客户端请求,如下所示:
Create(User) returns (Response);
Create(Permissions) returns (Response);
英文:
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);
答案1
得分: 1
你可以使用oneof
来允许客户端发送User
或Permissions
。请参考https://developers.google.com/protocol-buffers/docs/proto3#oneof
message Request {
oneof request {
User user = 1;
Permissions permissions = 2;
}
}
因此,客户端可以在请求中填充其中任何一个。
service DatabaseService {
rpc Create(Request) returns (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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论