-
Notifications
You must be signed in to change notification settings - Fork 7
/
marshal.go
69 lines (51 loc) · 1.11 KB
/
marshal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package qs
import (
"fmt"
"net/url"
)
func Marshal(hash map[string]interface{}) (string, error) {
return buildNestedQuery(hash, "")
}
func buildNestedQuery(value interface{}, prefix string) (string, error) {
components := ""
switch vv := value.(type) {
case []interface{}:
for i, v := range vv {
component, err := buildNestedQuery(v, prefix+"[]")
if err != nil {
return "", err
}
components += component
if i < len(vv)-1 {
components += "&"
}
}
case map[string]interface{}:
length := len(vv)
for k, v := range vv {
childPrefix := ""
if prefix != "" {
childPrefix = prefix + "[" + url.QueryEscape(k) + "]"
} else {
childPrefix = url.QueryEscape(k)
}
component, err := buildNestedQuery(v, childPrefix)
if err != nil {
return "", err
}
components += component
length -= 1
if length > 0 {
components += "&"
}
}
case string:
if prefix == "" {
return "", fmt.Errorf("value must be a map[string]interface{}")
}
components += prefix + "=" + url.QueryEscape(vv)
default:
components += prefix
}
return components, nil
}