-
Notifications
You must be signed in to change notification settings - Fork 4
/
form.go
85 lines (76 loc) · 1.84 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
// Content managed by Project Forge, see [projectforge.md] for details.
package cutil
import (
"encoding/xml"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"gopkg.in/yaml.v2"
"projectforge.dev/projectforge/app/util"
)
func ParseForm(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
ct := GetContentType(rc)
if IsContentTypeJSON(ct) {
return parseJSONForm(rc)
}
if IsContentTypeXML(ct) {
return parseXMLForm(rc)
}
if IsContentTypeYAML(ct) {
return parseYAMLForm(rc)
}
return parseHTTPForm(rc)
}
func ParseFormAsChanges(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
ret, err := ParseForm(rc)
if err != nil {
return nil, err
}
return ret.AsChanges()
}
func parseJSONForm(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
var ret any
err := util.FromJSON(rc.Request.Body(), &ret)
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(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
ret := util.ValueMap{}
err := xml.Unmarshal(rc.Request.Body(), &ret)
if err != nil {
return nil, errors.Wrap(err, "can't parse XML body")
}
return ret, nil
}
func parseYAMLForm(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
ret := util.ValueMap{}
err := yaml.Unmarshal(rc.Request.Body(), &ret)
if err != nil {
return nil, errors.Wrap(err, "can't parse YAML body")
}
return ret, nil
}
func parseHTTPForm(rc *fasthttp.RequestCtx) (util.ValueMap, error) {
f := rc.PostArgs()
ret := make(util.ValueMap, f.Len())
f.VisitAll(func(key []byte, value []byte) {
k := string(key)
xs := f.PeekMulti(k)
v := make([]string, 0, len(xs))
for _, x := range xs {
v = append(v, string(x))
}
if len(v) == 1 {
ret[k] = v[0]
} else {
ret[k] = v
}
})
return ret, nil
}