在 Go 中构建使用“oneof”的 protobuf 消息

Lia*_*rth 3 go protocol-buffers

我最近开始玩弄 GoLang 和 Protocol Buffers,我尝试使用以下消息

message KumoAPIMessage {
  oneof msg {
    OpenStackEnvironmentContext osEnvContext = 1;
  }
}

message OpenStackEnvironmentContext {
  string username = 1;
  string password = 2;
  string domain = 3;
  string project = 4;
  string authUrl = 6;
  string region = 7;
  string contextName = 8;
}
Run Code Online (Sandbox Code Playgroud)

这些消息经过精心设计,以便可以对其进行编组并通过 TCP 发送到服务器代理(用 Scala 编写)。我遇到的问题实际上是在 go 应用程序中构建消息。

我已经收到一条OpenStackEnvironmentContext消息,但我不知道如何将其包装在 中KumoAPIMessage,我尝试了以下方法

apiMessage := kumo.KumoAPIMessage{ Msg: context, }
Run Code Online (Sandbox Code Playgroud)

但这只会在编译时引发以下错误

cannot use context (type kumo.OpenStackEnvironmentContext) as type kumo.isKumoAPIMessage_Msg in field value:
kumo.OpenStackEnvironmentContext does not implement kumo.isKumoAPIMessage_Msg (missing kumo.isKumoAPIMessage_Msg method)
Run Code Online (Sandbox Code Playgroud)

如果有人知道我哪里出了问题,你将成为我的英雄。

Lia*_*rth 6

这一次我能够回答我自己的问题了。经过大量的谷歌搜索和实验,我得到了以下解决方案

apiMessage := &kumo.KumoAPIMessage{&kumo.KumoAPIMessage_OsEnvContext{context}}
Run Code Online (Sandbox Code Playgroud)

似乎 protobufs 的 GoLang 编译器为包装器消息生成一个结构体,并为它所包装的消息类型生成一个结构体