-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinder.go
More file actions
44 lines (37 loc) · 1.25 KB
/
binder.go
File metadata and controls
44 lines (37 loc) · 1.25 KB
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
package emir
import (
"encoding/json"
"encoding/xml"
"strings"
"github.com/pasztorpisti/qs"
)
// Bind implements the Binder#Bind function. Binding is done in following order:
// Binder will bind the body first then binds the query params
// If the request method is not POST, PUT or PATCH then the binder will skip the body
// Struct tag for query params will be "qs".
func (*DefaultBinder) Bind(c *Context, v interface{}) error {
contentType := B2S(c.ReqHeader().ContentType())
if c.IsPost() || c.IsPut() || c.IsPatch() {
switch {
case strings.HasPrefix(contentType, ContentTypeApplicationJSON):
if marshaler, ok := v.(json.Unmarshaler); ok {
if err := marshaler.UnmarshalJSON(c.PostBody()); err != nil {
return err
}
}
if err := json.Unmarshal(c.PostBody(), v); err != nil {
return err
}
case strings.HasPrefix(contentType, ContentTypeApplicationXML) ||
strings.HasPrefix(contentType, ContentTypeTextXML):
if err := xml.Unmarshal(c.PostBody(), v); err != nil {
return err
}
case strings.HasPrefix(contentType, ContentTypeApplicationForm):
if err := qs.UnmarshalValues(v, ConvertArgsToValues(c.PostArgs())); err != nil {
return err
}
}
}
return qs.UnmarshalValues(v, ConvertArgsToValues(c.QueryArgs()))
}