18

我正在使用 grpc golang 在客户端和服务器应用程序之间进行通信。下面是 protoc 缓冲区的代码。

syntax = "proto3";
package Trail;

service TrailFunc {
  rpc HelloWorld (Request) returns (Reply) {}
}

// The request message containing the user's name.
message Request {
  map<string,string> inputVar = 1;
}
// The response message containing the greetings
message Reply {
  string outputVar = 1;
}

我需要在消息数据结构中创建一个类型为 map[string]interface{} 的字段 inputVar,而不是 map[string]string。我怎样才能实现它?提前致谢。

4

3 回答 3

19

proto3 有类型Any

import "google/protobuf/any.proto";

message ErrorStatus {
  string message = 1;
  repeated google.protobuf.Any details = 2;
}

但如果你看一下它的实现,它就像

message Any {
  string type_url = 1;
  bytes value = 2;
}

您必须自己定义这样的消息,可能使用反射和中间类型。

查看示例应用程序

https://github.com/golang/protobuf/issues/60

于 2016-10-26T14:38:17.990 回答
6

了一篇较长的文章,介绍如何使用google.protobuf.Struct任意 JSON 输入。该structpb包能够通过其功能map[string]interface{}从 a中生成 a。structpb.StructAsMap()

官方文档:https ://pkg.go.dev/google.golang.org/protobuf/types/known/structpb

于 2020-11-26T17:37:45.227 回答
2

虽然处理起来有点冗长,但协议缓冲区中的“struct”类型可能更接近 golang 的 map[string]interface{}

但是像 interface{} 将需要一些反射式的开销来确定实际存储的类型是什么。

例如在这里查看评论:https ://github.com/golang/protobuf/issues/370

于 2017-07-03T22:14:38.160 回答