如何命名这些谷歌原型字段,以便我可以在GoLang中使用它们来接受特定的JSON?

我正在构建一个 gRPC 函数(称为 myFunc),该函数将以下 JSON 数据的等效项作为其参数:


{

  "id": "ABCD4435010",

  "otherId": "WXYZ4435010",

  "duration": 30

}

作为本练习的一部分,我需要设计原型布夫消息。它看起来像这样:


 1:    // MyFunc does something I guess.

 2:    rpc MyFunc(MyFuncRequest) returns (MyFuncResponse) {

 3:        option (google.api.http) = {

 4:            post: "/my.path.to.endpoint/MyFunc"

 5:            body: "*"

 6:        };

 7:    }

 8:

 9:    // MyFuncRequest is the request object for MyFunc.

10:    message MyFuncRequest {

11:        // id is something.

12:        string id = 1;

13:        // otherId is something.

14:        string otherId = 2;

15:        // duration is something.

16:        string duration = 3;

17:    }

当我尝试从中生成 golang 文件时,我收到以下错误:


myFile.proto:14:3:Field name "otherId" must be lower_snake_case.

myFile.proto:16:3:Field "duration" must be a google.protobuf.Duration.

这些错误的 2 个问题:


如果我更改为它将不再与 JSON 中的键名匹配。otherIdother_id

如果我将字段的类型更改为它将不再与JSON中的数据类型匹配。因此,编组/取消编组将失败。durationgoogle.protobuf.Duration

如何解决这些错误消息并让我的协议缓冲区编译?


绝地无双
浏览 121回答 3
3回答

呼啦一阵风

为原型布夫扩展指定 JSON 名称是你问题的答案吗?message TestMessage {     string other_id = 2 [json_name="otherId"]; }google.protobuf.Duration应该是一个字符串。在这里阅读评论

千巷猫影

我假设你正在得到,你想要.OtherIdotherId创建一个新类型并将其映射到原始生成的类型|可能是最简单的。这为您提供了所需的映射,而无需进行任何“杂技”来保持快乐并获得所需的JSON。protoc我很惊讶,它检测到并强制。您希望这是一个数字而不是一个字符串。您是否尝试过使用例如 在您的消息定义中,而不是(它不是)?durationuint32string

拉丁的传说

按照 grpc 快速入门指南 进入那里 网站() grpc.io/docs/languages/go/quickstartprotoc version 3通过更新他们的例子,在这里说改变你好请求如下,并按照这个命令重新生成grp代码。hello world    message HelloRequest {        // id is something.        string id = 1;        // otherId is something.        string otherId = 2;        // duration is something.        string duration = 3;    }重新生成命令    --go-grpc_out=. --go-grpc_opt=paths=source_relative \    helloworld/helloworld.proto它将使用您的字段创建 grpc 请求,而不会出现错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go