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

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

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来允许客户端发送UserPermissions。请参考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);
}

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:

确定