GRPC服务在GoLang中使用通用proto请求数据。

huangapple go评论118阅读模式
英文:

GRPC Service with Generic proto request data in GoLang

问题

我有3个proto文件,如下所示:

1 - record.proto

  1. message Record {
  2. int64 primaryKey = 1;
  3. int64 createdAt = 2;
  4. int64 updatedAt = 3;
  5. }

2 - user.proto

  1. import "record.proto";
  2. message User {
  3. Record record = 31;
  4. string name = 32;
  5. string email = 33;
  6. string password = 34;
  7. }

3 - permissions.proto

  1. import "record.proto";
  2. message Permissions{
  3. Record record = 31;
  4. string permission1= 32;
  5. string permission2= 33;
  6. }

问题1:
有没有办法在golang中实现一个grpc服务器和客户端,它接受Record作为请求,但同时也接受后面的两种类型,即User和Permissions。
类似这样:

  1. service DatabaseService {
  2. rpc Create(Record) returns (Response);
  3. }

这样我就可以发送grpc客户端请求,如下所示:

  1. Create(User) returns (Response);
  2. Create(Permissions) returns (Response);
英文:

I have 3 protos as follow:

1 - record.proto

  1. message Record {
  2. int64 primaryKey = 1;
  3. int64 createdAt = 2;
  4. int64 updatedAt = 3;
  5. }

2 - user.proto

  1. import "record.proto";
  2. message User {
  3. Record record = 31;
  4. string name = 32;
  5. string email = 33;
  6. string password = 34;
  7. }

3 - permissions.proto

  1. import "record.proto";
  2. message Permissions{
  3. Record record = 31;
  4. string permission1= 32;
  5. string permission2= 33;
  6. }

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:

  1. service DatabaseService {
  2. rpc Create(Record) returns (Response);
  3. }

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

  1. Create(User) returns (Response);
  2. Create(Permissions) returns (Response);

答案1

得分: 1

你可以使用oneof来允许客户端发送UserPermissions。请参考https://developers.google.com/protocol-buffers/docs/proto3#oneof

  1. message Request {
  2. oneof request {
  3. User user = 1;
  4. Permissions permissions = 2;
  5. }
  6. }

因此,客户端可以在请求中填充其中任何一个。

  1. service DatabaseService {
  2. rpc Create(Request) returns (Response);
  3. }
英文:

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

  1. message Request {
  2. oneof request {
  3. User user = 1;
  4. Permissions permissions = 2;
  5. }
  6. }

So client can fill any of them in the request.

  1. service DatabaseService {
  2. rpc Create(Request) returns (Response);
  3. }

huangapple
  • 本文由 发表于 2022年3月2日 17:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/71320369.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定