-
Notifications
You must be signed in to change notification settings - Fork 4
/
form.go
117 lines (106 loc) · 2.45 KB
/
form.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package cutil
import (
"net/http"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"projectforge.dev/projectforge/app/util"
)
func ParseForm(r *http.Request, b []byte) (util.ValueMap, error) {
ct := GetContentType(r)
if IsContentTypeJSON(ct) {
return parseJSONForm(b)
}
if IsContentTypeXML(ct) {
return parseXMLForm(b)
}
if IsContentTypeYAML(ct) {
return parseYAMLForm(b)
}
ret, err := parseJSONForm(b)
if err != nil {
ret, err = parseHTTPForm(r)
}
return ret, err
}
func ParseFormAsMaps(r *http.Request, rBody []byte) ([]util.ValueMap, error) {
frm, err := ParseForm(r, rBody)
if err != nil {
return nil, errors.Wrap(err, "unable to parse form")
}
switch {
case frm.HasKey("resultArray"):
return frm.GetMapArray("resultArray", false)
case frm.HasKey("json"):
var ret []util.ValueMap
js := frm.GetStringOpt("json")
m, err := util.FromJSONMap([]byte(js))
if err == nil {
ret = append(ret, m)
} else {
err = util.FromJSON([]byte(js), &ret)
if err != nil {
return nil, errors.Wrapf(err, "unable to parse JSON from [%s]", js)
}
}
return ret, nil
case len(frm) == 0:
return nil, errors.Errorf("unable to parse request body as events (no fields)")
default:
return []util.ValueMap{frm}, nil
}
}
func ParseFormAsChanges(r *http.Request, b []byte) (util.ValueMap, error) {
ret, err := ParseForm(r, b)
if err != nil {
return nil, err
}
return ret.AsChanges()
}
func parseJSONForm(b []byte) (util.ValueMap, error) {
ret, err := util.FromJSONAny(b)
if err != nil {
return nil, errors.Wrap(err, "can't parse JSON body")
}
switch t := ret.(type) {
case map[string]any:
return t, nil
default:
return util.ValueMap{"resultArray": t}, nil
}
}
func parseXMLForm(b []byte) (util.ValueMap, error) {
ret, err := util.FromXMLMap(b)
if err != nil {
return nil, errors.Wrap(err, "can't parse XML body")
}
return ret, nil
}
func parseYAMLForm(b []byte) (util.ValueMap, error) {
ret := util.ValueMap{}
err := yaml.Unmarshal(b, &ret)
if err != nil {
return nil, errors.Wrap(err, "can't parse YAML body")
}
return ret, nil
}
func parseHTTPForm(r *http.Request) (util.ValueMap, error) {
err := r.ParseForm()
if err != nil {
return nil, err
}
ret := make(util.ValueMap, len(r.PostForm))
for k, v := range r.PostForm {
if len(v) == 1 {
ret[k] = v[0]
} else {
ret[k] = v
}
}
return ret, nil
}
func CleanID(key string, id string) string {
if id == "" {
return key + "-" + util.RandomString(6)
}
return id
}