Reputation: 141
I'm fairly new to Go, so I apologize if this is a trivial question.
I'm currently trying to write a function that creates a POST request with a nested parameter hash. So the equivalent call in a dynamic language such as javascript would be:
$.post('http://example.com', {level1: {level2: 'foo'}});
In my Go code, I currently have have the hash nested in the following way:
func (runner *Runner) post(args... interface{}) interface{} {
form_url := getString(args[0])
form_data := ???
http.PostForm(form_url, form_data)
The actual type for the form data (interface{}) is provided by a 3rd party library, so I cannot really change it.
The problem is the PostForm expects a url.Values type for the form data, which is define as
type Values map[string][]string
What would be the best of handling this? My conclusion so far is that I would need to write a function that would HTTP encode the nested hash and have the following signature:
func httpEncodeNestedMap(data interface{}) map[string][]string {...}
What would be the idiomatic implementation of this in Go?
Thanks.
Upvotes: 4
Views: 2649
Reputation: 24808
Basically, in HTTP there is no 'nesting' of parameters per se. Some systems provide facilities to parse a query string in a way that simulates dimensions.
For example, PHP supports the []
-notation. In PHP you can have a query string like foo[bar]=baz&foo[zar]=boo
which would translate to a $_REQUEST
structure like this:
array(
'foo' => array(
'bar' => 'baz',
'zar' => 'boo'
)
)
The standard Go library does not provide such functionality for valid reasons. You can implement it on your own though.
What Go does support and PHP does not (at least not "natively") is multiple values for query parameters.
type Values map[string][]string
Note how any parameter name (string index) can have multiple values (slice of strings). This occurrs when your query string looks like foo=bar&foo=zar
, then you'd get:
map[string][]string {
"foo": {
"bar",
"zar"
}
}
I hope this clears things up.
Upvotes: 4