【问题标题】:Create variable of type Map[string]interface{} in gRPC protoc buffer golang在 gRPC 协议缓冲区 golang 中创建类型为 Map[string]interface{} 的变量
【发布时间】:2017-03-08 15:48:38
【问题描述】:

我正在使用 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。 我怎样才能实现它? 提前致谢。

【问题讨论】:

  • 副手,这听起来像“你不想”。但我猜map&lt;string,google.protobuf.Any&gt; 可能有用,也许吧?

标签: go grpc protoc


【解决方案1】:

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

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

example application

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

【讨论】:

    【解决方案2】:

    我在wrote 发表了一篇关于如何使用google.protobuf.Struct 处理任意 JSON 输入的较长文章。 structpb 包能够通过其AsMap() 函数从structpb.Struct 生成map[string]interface{}

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

    【讨论】:

      【解决方案3】:

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

      但是像 interface{} 一样会花费一些反射式的开销来确定实际存储的类型是什么。

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

      【讨论】:

        猜你喜欢
        • 2017-03-18
        • 1970-01-01
        • 2017-04-01
        • 1970-01-01
        • 2020-05-22
        • 2017-07-06
        • 2018-10-08
        • 1970-01-01
        • 2015-05-02
        相关资源
        最近更新 更多