-
Notifications
You must be signed in to change notification settings - Fork 180
/
bind.go
68 lines (60 loc) · 1.77 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
package dotweb
import (
"encoding/json"
"encoding/xml"
"errors"
"strings"
"github.com/devfeel/dotweb/framework/reflects"
)
const (
defaultTagName = "form"
jsonTagName = "json"
)
type (
// Binder is the interface that wraps the Bind method.
Binder interface {
Bind(interface{}, Context) error
BindJsonBody(interface{}, Context) error
}
binder struct{}
)
// Bind decode req.Body or form-value to struct
func (b *binder) Bind(i interface{}, ctx Context) (err error) {
req := ctx.Request()
ctype := req.Header.Get(HeaderContentType)
if req.Body == nil {
err = errors.New("request body can't be empty")
return err
}
err = errors.New("request unsupported MediaType -> " + ctype)
switch {
case strings.HasPrefix(ctype, MIMEApplicationJSON):
err = json.Unmarshal(ctx.Request().PostBody(), i)
case strings.HasPrefix(ctype, MIMEApplicationXML):
err = xml.Unmarshal(ctx.Request().PostBody(), i)
// case strings.HasPrefix(ctype, MIMEApplicationForm), strings.HasPrefix(ctype, MIMEMultipartForm),
// strings.HasPrefix(ctype, MIMETextHTML):
// err = reflects.ConvertMapToStruct(defaultTagName, i, ctx.FormValues())
default:
// check is use json tag, fixed for issue #91
tagName := defaultTagName
if ctx.HttpServer().ServerConfig().EnabledBindUseJsonTag {
tagName = jsonTagName
}
// no check content type for fixed issue #6
err = reflects.ConvertMapToStruct(tagName, i, ctx.Request().FormValues())
}
return err
}
// BindJsonBody default use json decode req.Body to struct
func (b *binder) BindJsonBody(i interface{}, ctx Context) (err error) {
if ctx.Request().PostBody() == nil {
err = errors.New("request body can't be empty")
return err
}
err = json.Unmarshal(ctx.Request().PostBody(), i)
return err
}
func newBinder() *binder {
return &binder{}
}