go - 如何为不同的 gRPC 端点重用 proto-buffer 消息?
问题描述
我有一个使用原始缓冲区(准确地说是 Proto3)的 Go 应用程序。
该应用程序有 2 个端点,A
定义B
如下:
rpc A(ARequest) returns (AResponse) {
option (google.api.http) = {
post: "/someURLA"
body: "*"
};
}
rpc B(BRequest) returns (BResponse) {
option (google.api.http) = {
put: "/someURLB"
body: "*"
};
}
以下是他们使用的消息:
message ARequest {
// Blah Blah Blah
}
message BRequest {
// Blah Blah Blah
}
message AResponse {
// Blah Blah Blah
}
message BResponse {
// Blah Blah Blah
}
端点实际上需要相同的输入格式A
并B
具有相同的输出格式。SoARequest
等同于BRequest
和AResponse
等同于BResponse
。但是 protofile 中的这些重复定义非常浪费,并且可能会出现分歧。所以我把它改成这样:
rpc A(AOrBRequest) returns (AOrBResponse) {
option (google.api.http) = {
post: "/someURLA"
body: "*"
};
}
rpc B(AOrBRequest) returns (AOrBResponse) {
option (google.api.http) = {
put: "/someURLB"
body: "*"
};
}
message AOrBRequest {
// Blah Blah Blah
}
message AOrBResponse {
// Blah Blah Blah
}
但是当我这样做时,我在编译过程中遇到了这些错误:
Name of request type "AOrBRequest" should be "ARequest".
Name of response type "AOrBResponse" should be "AResponse"
Name of request type "AOrBRequest" should be "BRequest".
Name of response type "AOrBResponse" should be "BResponse"
那么如何让这两个端点对请求和响应重用相同的消息呢?
解决方案
您可以使用import 语句来重用消息定义。
您可以通过导入其他 .proto 文件中的定义来使用它们。要导入另一个 .proto 的定义,请在文件顶部添加一个 import 语句:
import "myproject/other_protos.proto";
例如,如果您下载了 Protocol Buffers 二进制包,readme.txt
存档中的内容会显示:
如果您打算使用包含的众所周知的类型,那么不要忘记将
include
目录的内容也复制到某处,例如复制到/usr/local/include/
.
如果你已经这样做了,你现在可以导入(或重复使用,如你所说)谷歌定义的消息。
syntax = "proto3";
package mypackage;
import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto";
service Bla {
rpc ResetUserPW(UserEmail) returns (google.protobuf.Empty) {}
rpc ServerTime(google.protobuf.Empty) returns (google.protobuf.Timestamp) {}
}
message UserEmail {
string email = 1;
CallBackUrl url = 2;
}
推荐阅读
- vim - Vim 无法识别 l 键 &
- python-3.x - 错误:Google Translate API 中的 503 DNS 解析失败,但仅在通过终端执行 Python 文件时
- r - 循环句子以查看句子是否包含触发词
- javascript - 如何让用户登录我的网站并知道他是否已登录
- google-apps-script - 是否有一个脚本可以在列表中的所有单元格上创建链接,并且一旦您单击它们将您发送到相应的(同名)选项卡?
- reactjs - 输入后如何保持搜索状态?
- xamarin - Xamarin - 将 ActivityIndicator 可见性绑定到异步任务完成
- html - 为什么导航栏不在顶部?
- sql - 在 SQL 中是否有更简洁或更简单的方法来实现这一点?
- jquery - ma5menu 移动菜单未关闭