正确使用 map[string]interface{} 是什么意思?

huangapple go评论84阅读模式
英文:

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 => valuekey => key => value等块发送到我们的 API 端点。

问题1:

如何给Request.Values赋值?我们可能需要使用以下示例用例(请原谅 PHP 代码,我们正在过渡):

'name' => [ $first, $last ],
'address' => [ 'city' => 'city', 'state' => 'state' ],
'country' => 'US'

在这个示例中,我们有key => valuekey => [ 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.

huangapple
  • 本文由 发表于 2013年9月11日 08:05:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/18730684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定