英文:
How do I pass a json body request to api in a map string data structure in Golang?
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对golang和grpc还不熟悉,需要指导和澄清。我有以下定义作为调用外部API的POST请求的参数。
params := map[string]string{
"movie": movie,
"seat": seat,
"pax": fmt.Sprint(pax),
"class": class,
}
在proto文件中,我有以下定义:
message TicketData {
string movie = 1;
string seat = 2;
uint32 pax = 3;
string class = 4;
}
message SearchMovieRequest {
TicketData data = 1;
}
然而,在POSTMAN(grpc请求)中,请求体显示如下:
{
"data": {
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
}
请求体应该如下所示:
{
"data": [
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
]
}
我的JSON请求体中缺少方括号。我尝试使用structpb和map string interface,但似乎不起作用。任何指针将不胜感激。谢谢。
英文:
I am new to golang and grpc, need guidance and clarification. I have below definition as a parameter to call a POST request for an external API.
params := map[string]string{
"movie": movie,
"seat": seat,
"pax": fmt.Sprint(pax),
"class": class,
}
In proto file, I have below:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
TicketData data= 1;
}
However in POSTMAN (grpc request), the body request is showing below:
{
"data":
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
}
the request body should be below:
{
"data": **[**
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
**]** - missing brackets in my json body
}
I have tried using structpb and also map string interface. It doesn't seem to work. Any pointer will be appreciated. Thank you.
答案1
得分: 2
你想要将data
字段设置为repeated TicketData
。
请参考Protobuf [Language Guide (proto3)]中的Specifying Field Rules。
具体来说:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
repeated TicketData data= 1;
}
> 注意 虽然你包含了Protobuf定义,但你的示例是JSON格式的。Protobuf实现通常包括Protobuf和JSON之间的自动映射,我猜这就是你展示的内容。
英文:
You want the data
field to be repeated TicketData
.
See e.g. Specifying Field Rules in the Protobuf Language Guide (proto3).
Specifically:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
repeated TicketData data= 1;
}
> NOTE Although you include protobuf definitions, your examples are JSON. Protobuf implementations usually include automatic mappings between protobuf and JSON which is -- I assume -- what you're presenting.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论