forked from storezhang/echox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
binder.go
358 lines (314 loc) · 9.45 KB
/
binder.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package echox
import (
`bytes`
`encoding`
`encoding/json`
`encoding/xml`
`errors`
`net/http`
`reflect`
`strconv`
`strings`
`github.com/labstack/echo/v4`
`github.com/storezhang/mengpo`
`github.com/vmihailenco/msgpack/v5`
`google.golang.org/protobuf/proto`
)
type binder struct {
tagParam string
tagQuery string
tagForm string
tagHeader string
tagDefault string
}
func (b *binder) Bind(value interface{}, ctx echo.Context) (err error) {
// 处理默认值
defer func() {
err = mengpo.Set(value, mengpo.Tag(b.tagDefault))
}()
if err = b.params(ctx, value); nil != err {
return
}
if err = b.headers(ctx, value); nil != err {
return
}
if http.MethodGet == ctx.Request().Method || http.MethodDelete == ctx.Request().Method {
if err = b.queries(ctx, value); nil != err {
return
}
}
// 只有在Content-Type设置值后才绑定Body
contentType := ctx.Request().Header.Get(HeaderContentType)
if "" == contentType {
return
}
if err = b.body(ctx, contentType, value); nil != err {
return
}
return
}
func (b *binder) params(ctx echo.Context, value interface{}) (err error) {
names := ctx.ParamNames()
values := ctx.ParamValues()
params := map[string][]string{}
for index, name := range names {
params[name] = []string{values[index]}
}
if err = b.bindData(value, params, b.tagParam); nil != err {
err = echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
return
}
func (b *binder) queries(ctx echo.Context, value interface{}) (err error) {
if err = b.bindData(value, ctx.QueryParams(), b.tagQuery); nil != err {
err = echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
return
}
func (b *binder) headers(ctx echo.Context, i interface{}) (err error) {
if err = b.bindData(i, ctx.Request().Header, b.tagHeader); nil != err {
err = echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
return
}
func (b *binder) body(ctx echo.Context, contentType string, value interface{}) (err error) {
req := ctx.Request()
if req.ContentLength == 0 {
return
}
switch {
case strings.HasPrefix(contentType, MIMEApplicationJSON):
err = json.NewDecoder(req.Body).Decode(value)
case strings.HasPrefix(contentType, MIMEApplicationXML), strings.HasPrefix(contentType, MIMETextXML):
err = xml.NewDecoder(req.Body).Decode(value)
case strings.HasPrefix(contentType, MIMEApplicationProtobuf):
buf := new(bytes.Buffer)
if _, err = buf.ReadFrom(req.Body); nil != err {
return
}
err = proto.Unmarshal(buf.Bytes(), value.(proto.Message))
case strings.HasPrefix(contentType, MIMEApplicationMsgpack):
err = msgpack.NewDecoder(req.Body).Decode(value)
case strings.HasPrefix(contentType, MIMEApplicationForm), strings.HasPrefix(contentType, MIMEMultipartForm):
var params map[string][]string
if params, err = ctx.FormParams(); nil != err {
return
}
err = b.bindData(value, params, b.tagForm)
case strings.HasPrefix(contentType, MIMEOctetStream):
buf := new(bytes.Buffer)
if _, err = buf.ReadFrom(req.Body); nil != err {
return
}
b.bindBytes(value, buf.Bytes())
}
return
}
func (b *binder) bindBytes(destination interface{}, bytes []byte) {
typ := reflect.TypeOf(destination).Elem()
val := reflect.ValueOf(destination).Elem()
for index := 0; index < typ.NumField(); index++ {
typeField := typ.Field(index)
structField := val.Field(index)
// 检查字段必须是[]byte
if !structField.CanSet() || reflect.Slice != typeField.Type.Kind() || reflect.Uint8 != structField.Type().Elem().Kind() {
continue
}
slice := reflect.MakeSlice(structField.Type(), len(bytes), len(bytes))
reflect.Copy(slice, reflect.ValueOf(bytes))
val.Field(index).Set(slice)
}
return
}
func (b *binder) bindData(destination interface{}, data map[string][]string, tag string) (err error) {
if nil == destination || 0 == len(data) {
return
}
typ := reflect.TypeOf(destination).Elem()
val := reflect.ValueOf(destination).Elem()
if typ.Kind() == reflect.Map {
for k, v := range data {
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0]))
}
return
}
if typ.Kind() != reflect.Struct {
if tag == b.tagParam || tag == b.tagQuery || tag == b.tagHeader {
// incompatible type, data is probably to be found in the body
return nil
}
return errors.New("binding element must be a struct")
}
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
structField := val.Field(i)
if typeField.Anonymous {
if structField.Kind() == reflect.Ptr {
structField = structField.Elem()
}
}
if !structField.CanSet() {
continue
}
structFieldKind := structField.Kind()
inputFieldName := typeField.Tag.Get(tag)
if typeField.Anonymous && structField.Kind() == reflect.Struct && inputFieldName != "" {
// if anonymous struct with query/param/form tags, report an error
return errors.New("query/param/form tags are not allowed with anonymous struct field")
}
if inputFieldName == "" {
// If tag is nil, we inspect if the field is a not BindUnmarshaler struct and try to bind data into it (might contains fields with tags).
// structs that implement BindUnmarshaler are binded only when they have explicit tag
if _, ok := structField.Addr().Interface().(echo.BindUnmarshaler); !ok && structFieldKind == reflect.Struct {
if err := b.bindData(structField.Addr().Interface(), data, tag); err != nil {
return err
}
}
// does not have explicit tag and is not an ordinary struct - so move to next field
continue
}
inputValue, exists := data[inputFieldName]
if !exists {
// Go json.Unmarshal supports case insensitive binding. However the
// url params are bound case sensitive which is inconsistent. To
// fix this we must check all of the map values in a
// case-insensitive search.
for k, v := range data {
if strings.EqualFold(k, inputFieldName) {
inputValue = v
exists = true
break
}
}
}
if !exists {
continue
}
// Call this first, in case we're dealing with an alias to an array type
if ok, err := unmarshalField(typeField.Type.Kind(), inputValue[0], structField); ok {
if err != nil {
return err
}
continue
}
numElems := len(inputValue)
if structFieldKind == reflect.Slice && numElems > 0 {
sliceOf := structField.Type().Elem().Kind()
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for j := 0; j < numElems; j++ {
if err := setWithProperType(sliceOf, inputValue[j], slice.Index(j)); err != nil {
return err
}
}
val.Field(i).Set(slice)
} else if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
return err
}
}
return nil
}
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) (err error) {
var ok bool
if ok, err = unmarshalField(valueKind, val, structField); ok {
return
}
switch valueKind {
case reflect.Ptr:
err = setWithProperType(structField.Elem().Kind(), val, structField.Elem())
case reflect.Int:
err = setIntField(val, 0, structField)
case reflect.Int8:
err = setIntField(val, 8, structField)
case reflect.Int16:
err = setIntField(val, 16, structField)
case reflect.Int32:
err = setIntField(val, 32, structField)
case reflect.Int64:
err = setIntField(val, 64, structField)
case reflect.Uint:
err = setUintField(val, 0, structField)
case reflect.Uint8:
err = setUintField(val, 8, structField)
case reflect.Uint16:
err = setUintField(val, 16, structField)
case reflect.Uint32:
err = setUintField(val, 32, structField)
case reflect.Uint64:
err = setUintField(val, 64, structField)
case reflect.Bool:
err = setBoolField(val, structField)
case reflect.Float32:
err = setFloatField(val, 32, structField)
case reflect.Float64:
err = setFloatField(val, 64, structField)
case reflect.String:
structField.SetString(val)
default:
err = errors.New("unknown type")
}
return
}
func unmarshalField(valueKind reflect.Kind, val string, field reflect.Value) (bool, error) {
switch valueKind {
case reflect.Ptr:
return unmarshalFieldPtr(val, field)
default:
return unmarshalFieldNonPtr(val, field)
}
}
func unmarshalFieldNonPtr(value string, field reflect.Value) (bool, error) {
fieldIValue := field.Addr().Interface()
if unmarshaler, ok := fieldIValue.(echo.BindUnmarshaler); ok {
return true, unmarshaler.UnmarshalParam(value)
}
if unmarshaler, ok := fieldIValue.(encoding.TextUnmarshaler); ok {
return true, unmarshaler.UnmarshalText([]byte(value))
}
return false, nil
}
func unmarshalFieldPtr(value string, field reflect.Value) (bool, error) {
if field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
return unmarshalFieldNonPtr(value, field.Elem())
}
func setIntField(value string, bitSize int, field reflect.Value) error {
if "" == value {
value = "0"
}
intVal, err := strconv.ParseInt(value, 10, bitSize)
if err == nil {
field.SetInt(intVal)
}
return err
}
func setUintField(value string, bitSize int, field reflect.Value) error {
if "" == value {
value = "0"
}
uintVal, err := strconv.ParseUint(value, 10, bitSize)
if err == nil {
field.SetUint(uintVal)
}
return err
}
func setBoolField(value string, field reflect.Value) error {
if "" == value {
value = "false"
}
boolVal, err := strconv.ParseBool(value)
if err == nil {
field.SetBool(boolVal)
}
return err
}
func setFloatField(value string, bitSize int, field reflect.Value) error {
if "" == value {
value = "0.0"
}
floatVal, err := strconv.ParseFloat(value, bitSize)
if err == nil {
field.SetFloat(floatVal)
}
return err
}