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
|
package http
import (
"strings"
"net/http"
)
const maxLevel = 127
type dataTree map[string]interface{}
// parsePost parses incoming request body into data tree.
func parsePost(r *http.Request) (dataTree, error) {
data := make(dataTree)
for k, v := range r.PostForm {
data.push(k, v)
}
for k, v := range r.MultipartForm.Value {
data.push(k, v)
}
return data, nil
}
func (d dataTree) push(k string, v []string) {
if len(v) == 0 {
// skip empty values
return
}
indexes := make([]string, 0)
for _, index := range strings.Split(k, "[") {
indexes = append(indexes, strings.Trim(index, "]"))
}
if len(indexes) <= maxLevel {
d.mount(indexes, v)
}
}
// mount mounts data tree recursively.
func (d dataTree) mount(i []string, v []string) {
if len(v) == 0 {
return
}
if len(i) == 1 {
// single value context
d[i[0]] = v[0]
return
}
if len(i) == 2 && i[1] == "" {
// non associated array of elements
d[i[0]] = v
return
}
if p, ok := d[i[0]]; ok {
p.(dataTree).mount(i[1:], v)
}
d[i[0]] = make(dataTree)
d[i[0]].(dataTree).mount(i[1:], v)
}
|