登录
首页 >  Golang >  Go问答

如何在 gRPC 中重用原始缓冲区消息以供多个端点使用?

来源:stackoverflow

时间:2024-02-25 08:42:25 442浏览 收藏

哈喽!今天心血来潮给大家带来了《如何在 gRPC 中重用原始缓冲区消息以供多个端点使用?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我有一个使用 proto-buffers(准确地说是 proto3)的 go 应用程序。

此应用程序有 2 个端点,ab 定义如下:

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   
}

端点 ab 实际上需要相同的输入格式并具有相同的输出格式。因此 arequestbrequest 相同,并且 aresponsebresponse 相同。但是原型文件中的这些重复定义非常浪费并且可能会产生分歧。所以我把它改成这样:

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 statements 重用消息定义。

例如,如果您下载了 protocol buffers 二进制包,则存档中的 readme.txt 会显示:

如果您已完成此操作,您现在可以导入(或按您的说法重复使用)google 定义的消息。

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;
}

好了,本文到此结束,带大家了解了《如何在 gRPC 中重用原始缓冲区消息以供多个端点使用?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>