-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbind.go
110 lines (91 loc) · 2.19 KB
/
bind.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
package THz
import (
"encoding/json"
"errors"
"net/url"
"go.x2ox.com/THz/internal/formdata"
"go.x2ox.com/THz/internal/header"
"go.x2ox.com/THz/internal/urlquery"
"go.x2ox.com/sorbifolia/pyrokinesis"
)
type Binding interface {
Bind(*Context, any) error
}
type (
_Bind struct{}
_BindAll struct{}
_BindForm struct{}
_BindPostForm struct{}
_BindURLQuery struct{}
_BindHeader struct{}
_BindJSON struct{}
)
func (_Bind) Bind(c *Context, a any) error {
contentType := c.fc.Request.Header.ContentType()
if len(contentType) == 0 {
return _BindURLQuery{}.Bind(c, a)
}
switch filterFlags(pyrokinesis.Bytes.ToString(contentType)) {
case "application/json":
return _BindJSON{}.Bind(c, a)
case "application/x-www-form-urlencoded":
return _BindPostForm{}.Bind(c, a)
case "multipart/form-data":
return _BindForm{}.Bind(c, a)
}
return errors.New("ContentType no support")
}
func (_BindAll) Bind(c *Context, a any) error {
if err := (_Bind{}).Bind(c, a); err != nil {
return err
}
if err := (_BindURLQuery{}).Bind(c, a); err != nil {
return err
}
if err := (_BindHeader{}).Bind(c, a); err != nil {
return err
}
return nil
}
func (_BindJSON) Bind(c *Context, a any) error {
body, err := c.fc.Request.BodyUncompressed()
if err != nil {
return err
}
return json.Unmarshal(body, a)
}
func (_BindHeader) Bind(c *Context, a any) error { return header.Parse(&c.fc.Request.Header, a) }
func (_BindForm) Bind(c *Context, a any) error {
f, err := c.fc.Request.MultipartForm()
if err != nil {
return err
}
return formdata.Parse(f, a)
}
func (_BindURLQuery) Bind(c *Context, a any) error {
u := pyrokinesis.Bytes.ToString(c.fc.URI().QueryString())
val, err := url.ParseQuery(u)
if err != nil {
return err
}
return urlquery.Parse(val, a)
}
func (_BindPostForm) Bind(c *Context, a any) error {
u, err := url.Parse(pyrokinesis.Bytes.ToString(c.fc.Request.Body()))
if err != nil {
return err
}
var val url.Values
if val, err = url.ParseQuery(u.RawQuery); err != nil {
return err
}
return urlquery.Parse(val, a)
}
func filterFlags(content string) string {
for i, char := range content {
if char == ' ' || char == ';' {
return content[:i]
}
}
return content
}