英文:
Properly using map[string]interface{}?
问题
我有两个相关的问题,我不想为这两个问题分别开启新的线程:
给定以下代码:
1 type Request struct {
2 Values map[string]interface{}
3 }
4
5 func (r Request) Send() {
6 client := &http.Client{}
7 resp, _ := http.Post("http://example.com", "text/json", &r.Values)
8 }
想法是能够将一个未知数量的key => value
,key => key => value
等块发送到我们的 API 端点。
问题1:
如何给Request.Values
赋值?我们可能需要使用以下示例用例(请原谅 PHP 代码,我们正在过渡):
'name' => [ $first, $last ],
'address' => [ 'city' => 'city', 'state' => 'state' ],
'country' => 'US'
在这个示例中,我们有key => value
,key => [ values ]
和key => [ key => value ]
。
我该如何将这些值赋给Request.Values
?
问题2:
显然Values
的类型是map[string]interface{}
,我该如何将其转换为io.Reader
类型,以便将值发送到服务器?
非常感谢您对这两个问题的任何指导。
英文:
I have two related questions, I did not want to open a new thread for both questions:
Given the following code:
1 type Request struct {
2 Values map[string]interface{}
3 }
4
5 func (r Request) Send() {
6 client := &http.Client{}
7 resp, _ := http.Post("http://example.com", "text/json", &r.Values)
8 }
The idea is to be able to send a block of an unknown amount key => value
, key => key => value
, etc. to our API endpoint.
Question 1:
How do I assign to Request.Values
? An example use case we may need to employ is the following (Excuse the PHP Code, we're transitioning):
'name' => [ $first, $last ],
'address' => [ 'city' => 'city', 'state' => 'state' ],
'country' => 'US'
In this example we have key => value
, key => [ values ]
, and key => [ key => value ]
How can I take that and assign the exact same values to Request.Values
?
Question 2:
Obviously Values
is of type map[string]interface{}
, how can I convert that to type io.Reader
so I can send the values to the server?
Any guidance is greatly appreciated on both questions.
答案1
得分: 6
问题1
您可以像对待其他值一样为Request.Values
分配值。
示例(在play中查看):
x := map[string]interface{}{
"foo": []string{"a","b"},
"bar": "foo",
"baz": 10.4,
}
问题2
您需要一个中间格式,例如JSON。
使用此包,您可以将Request
结构体编组为JSON字符串,传输该字符串,然后在另一端(PHP?)解析它。
英文:
Question 1
You can assign values to Request.Values
just like with any other value.
Example (on play):
x := map[string]interface{}{
"foo": []string{"a","b"},
"bar": "foo",
"baz": 10.4,
}
Question 2
You are in need of an intermediate format, for example JSON.
With this package you can marshal your Request
struct to a JSON string, transfer
said string and parse it on the other (PHP?) side.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论