-
Notifications
You must be signed in to change notification settings - Fork 52
/
bind_value.go
93 lines (85 loc) · 1.91 KB
/
bind_value.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
package znet
import (
"reflect"
"github.com/sohaha/zlsgo/zjson"
"github.com/sohaha/zlsgo/zreflect"
)
func (c *Context) Bind(obj interface{}) (err error) {
method := c.Request.Method
if method == "GET" {
return c.BindQuery(obj)
}
contentType := c.ContentType()
if contentType == c.ContentType(ContentTypeJSON) {
return c.BindJSON(obj)
}
return c.BindForm(obj)
}
func (c *Context) BindJSON(obj interface{}) error {
body, err := c.GetDataRaw()
if err != nil {
return err
}
return zjson.Unmarshal(body, obj)
}
func (c *Context) BindQuery(obj interface{}) (err error) {
q := c.GetAllQueryMaps()
if err != nil {
return err
}
typ, err := zreflect.NewTyp(reflect.TypeOf(obj))
if err != nil {
return err
}
m := make(map[string]interface{}, len(q))
err = typ.ForEach(func(parent []string, index int, tag string, field reflect.StructField) error {
kind := field.Type.Kind()
if kind == reflect.Struct {
m[tag] = c.QueryMap(tag)
} else if kind == reflect.Slice {
v, _ := c.GetQueryArray(tag)
m[tag] = v
} else {
v, ok := q[tag]
if ok {
m[tag] = v
}
}
return zreflect.SkipStruct
})
if err != nil {
return err
}
return zreflect.Map2Struct(m, obj)
}
func (c *Context) BindForm(obj interface{}) error {
q := c.GetPostFormAll()
typ, err := zreflect.NewTyp(reflect.TypeOf(obj))
if err != nil {
return err
}
m := make(map[string]interface{}, len(q))
err = typ.ForEach(func(parent []string, index int, tag string, field reflect.StructField) error {
kind := field.Type.Kind()
if kind == reflect.Struct {
m[tag] = c.PostFormMap(tag)
} else if kind == reflect.Slice {
sliceTyp := field.Type.Elem().Kind()
if sliceTyp == reflect.Struct {
// todo follow up support
} else {
m[tag], _ = q[tag]
}
} else {
v, ok := q[tag]
if ok {
m[tag] = v[0]
}
}
return zreflect.SkipStruct
})
if err != nil {
return err
}
return zreflect.Map2Struct(m, obj)
}