英文:
Create variable of type Map[string]interface{} in gRPC protoc buffer golang
问题
我正在使用gRPC的Go语言实现来实现客户端和服务器应用程序之间的通信。
以下是protoc buffer的代码。
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
。我该如何实现呢?
提前感谢。
英文:
I'm using grpc golang to communicate between client and server application.
Below is the code for protoc buffer.
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;
}
I need to create a field inputVar of type map[string]interface{} inside message data structure instead of map[string]string.
How can I achieve it?
Thanks in advance.
答案1
得分: 21
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
英文:
proto3 has type Any
import "google/protobuf/any.proto";
message ErrorStatus {
string message = 1;
repeated google.protobuf.Any details = 2;
}
but if you look at its implementation, it is simply as
message Any {
string type_url = 1;
bytes value = 2;
}
You have to define such a message yourself by possibly using reflection and an intermediate type.
答案2
得分: 12
我写了一篇更长的帖子,介绍如何使用google.protobuf.Struct
来处理任意的JSON输入。structpb
包可以通过其AsMap()
函数从structpb.Struct
生成一个map[string]interface{}
。
官方文档:https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb
英文:
I wrote a longer post about how to use google.protobuf.Struct
to work with arbitrary JSON input. The structpb
package capable to produce a map[string]interface{}
from a structpb.Struct
via its AsMap()
function.
Official documentation: https://pkg.go.dev/google.golang.org/protobuf/types/known/structpb
答案3
得分: 4
尽管处理起来有点冗长,但协议缓冲区中的"struct"类型可能更接近于Go语言的map[string]interface{}。
但是,与interface{}一样,需要一些反射式的开销来确定实际存储的类型。
例如,请参见此处的评论:https://github.com/golang/protobuf/issues/370
英文:
While it gets a little verbose to deal with, the "struct" type in protocol buffers is probably closer to golang's map[string]interface{}
But like interface{} will take some reflection-style overhead to determine what the actual stored type is.
for example see comment here: https://github.com/golang/protobuf/issues/370
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论