go - protoc-gen-go struct xxx 隐蔽到 map[string]interface{}

标签 go protocol-buffers grpc protoc grpc-go

.proto文件生成的.pb.go文件中的struct多了三个字段和一些其他的东西。像这样:

enter image description here

将此struct转为json时,如果有一个字段为空,则该字段不会出现在json中。现在我知道可以使用 jsonpb.Marshaler 来完成。

m := jsonpb.Marshaler{EmitDefaults: true}

现在,我将 struct 转换为 ma​​p[string]interface{},将其放入 InfluxDB。我必须将结构转换为 map[string]interface{}。函数 NewPoint 需要。像这样: enter image description here enter image description here

enter image description here

我在go中使用了structs.Map(value)函数,转换后的map多了三个字段,运行程序报错,像这样:

{"error":"unable to parse 'txt,severity=1 CurrentValue=\"1002\",MetricAlias=\"CPU\",XXX_sizecache=0i,XXX_unrecognized= 1552551101': missing field value"}

当我去掉这三个字段后,程序运行正常。这三个字段是自动生成的,我有很多结构体。 我该怎么办?谢谢!

最佳答案

Protobuf 生成器添加了一些名称以 XXX 开头的额外字段,用于优化。您无法更改 protoc-gen-go 的这种行为。

问题在于将 struct 转换为 map[sting]interface{} 的方式。很难弄清楚 structs.Map 究竟来自哪个包。似乎从这里开始:https://github.com/fatih/structs/blob/master/structs.go#L89 - 此代码使用 reflect 遍历结构的所有字段并将它们推送到 map[sting]interface{}。您只需编写您自己的 FillMap 例程的略微修改版本,该例程将省略 XXX 字段。

关于go - protoc-gen-go struct xxx 隐蔽到 map[string]interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159445/

相关文章:

variables - 在 Go 中设置全局条件变量

loops - 功能中的循环问题

C++ "error: no type named ‘type’ 在 ‘class std::result_of< ... >"

go - 如何省略结构字段

asp.net - Google Protocol Buffers 或类似的 .net/javascript

c++ - 在 C++ 中使用 gRPC 时未解析的外部符号

php - 对话流 API : Retrieve extracted parameters from Detect intent response

python - 如何在python中配置gRPC HTTP/2流量控制

java - 如何在 java/android 中的 GRPC 中导入 .proto 文件中的数据类型?

mysql - 戈朗 : Decode json string to struct from mysql db