-
Notifications
You must be signed in to change notification settings - Fork 11
/
binder.go
534 lines (504 loc) · 13.4 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package echo
import (
"encoding/xml"
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"unicode"
"github.com/webx-top/echo/encoding/json"
"github.com/webx-top/tagfast"
"github.com/webx-top/validation"
)
// DefaultHTMLFilter html filter (`form_filter:"html"`)
var DefaultHTMLFilter = func(v string) (r string) {
return v
}
type (
// Binder is the interface that wraps the Bind method.
Binder interface {
Bind(interface{}, Context, ...FormDataFilter) error
MustBind(interface{}, Context, ...FormDataFilter) error
}
binder struct {
*Echo
decoders map[string]func(interface{}, Context, ...FormDataFilter) error
}
)
func NewBinder(e *Echo) Binder {
return &binder{
Echo: e,
decoders: map[string]func(interface{}, Context, ...FormDataFilter) error{
MIMEApplicationJSON: func(i interface{}, ctx Context, filter ...FormDataFilter) error {
body := ctx.Request().Body()
if body == nil {
return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
}
defer body.Close()
return json.NewDecoder(body).Decode(i)
},
MIMEApplicationXML: func(i interface{}, ctx Context, filter ...FormDataFilter) error {
body := ctx.Request().Body()
if body == nil {
return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
}
defer body.Close()
return xml.NewDecoder(body).Decode(i)
},
MIMEApplicationForm: func(i interface{}, ctx Context, filter ...FormDataFilter) error {
body := ctx.Request().Body()
if body == nil {
return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
}
defer body.Close()
return NamedStructMap(ctx.Echo(), i, ctx.Request().PostForm().All(), ``, filter...)
},
MIMEMultipartForm: func(i interface{}, ctx Context, filter ...FormDataFilter) error {
body := ctx.Request().Body()
if body == nil {
return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
}
defer body.Close()
return NamedStructMap(ctx.Echo(), i, ctx.Request().Form().All(), ``, filter...)
},
},
}
}
func (b *binder) MustBind(i interface{}, c Context, filter ...FormDataFilter) error {
contentType := c.Request().Header().Get(HeaderContentType)
contentType = strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, `;`, 2)[0]))
if decoder, ok := b.decoders[contentType]; ok {
return decoder(i, c, filter...)
}
return ErrUnsupportedMediaType
}
func (b *binder) Bind(i interface{}, c Context, filter ...FormDataFilter) (err error) {
err = b.MustBind(i, c, filter...)
if err == ErrUnsupportedMediaType {
err = nil
}
return
}
func (b *binder) SetDecoders(decoders map[string]func(interface{}, Context, ...FormDataFilter) error) {
b.decoders = decoders
}
func (b *binder) AddDecoder(mime string, decoder func(interface{}, Context, ...FormDataFilter) error) {
b.decoders[mime] = decoder
}
// FormNames user[name][test]
func FormNames(s string) []string {
var res []string
hasLeft := false
hasRight := true
var val []rune
for _, r := range s {
if r == '[' {
if hasRight {
res = append(res, string(val))
val = []rune{}
}
hasLeft = true
hasRight = false
continue
}
if r == ']' {
if hasLeft {
hasRight = true
}
continue
}
val = append(val, r)
}
if len(val) > 0 {
res = append(res, string(val))
}
return res
}
// NamedStructMap 自动将map值映射到结构体
func NamedStructMap(e *Echo, m interface{}, data map[string][]string, topName string, filters ...FormDataFilter) error {
vc := reflect.ValueOf(m)
tc := reflect.TypeOf(m)
switch tc.Kind() {
case reflect.Struct:
case reflect.Ptr:
vc = vc.Elem()
tc = tc.Elem()
default:
return errors.New(`binder: unsupported type ` + tc.Kind().String())
}
var (
validator *validation.Validation
filter FormDataFilter
)
if len(filters) > 0 {
filter = filters[0]
}
if filter == nil {
filter = DefaultNopFilter
}
for k, t := range data {
k, t = filter(k, t)
if len(k) == 0 || k[0] == '_' {
continue
}
if len(topName) > 0 {
if !strings.HasPrefix(k, topName) {
continue
}
k = k[len(topName)+1:]
}
v := t[0]
names := strings.Split(k, `.`)
var (
err error
propPath string
)
length := len(names)
if length == 1 && strings.HasSuffix(k, `]`) {
names = FormNames(k)
length = len(names)
}
value := vc
typev := tc
for i, name := range names {
name = strings.Title(name)
if i > 0 {
propPath += `.`
}
propPath += name
//不是最后一个元素
if i != length-1 {
if value.Kind() != reflect.Struct {
e.Logger().Warnf(`binder: arg error, value kind is %v`, value.Kind())
break
}
f, _ := typev.FieldByName(name)
if tagfast.Value(tc, f, `form_options`) == `-` {
break
}
value = value.FieldByName(name)
if !value.IsValid() {
e.Logger().Debugf(`binder: %T#%v value is not valid %v`, m, propPath, value)
break
}
if !value.CanSet() {
e.Logger().Warnf(`binder: can not set %T#%v -> %v`, m, propPath, value.Interface())
break
}
if value.Kind() == reflect.Ptr {
if value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
value = value.Elem()
}
if value.Kind() != reflect.Struct {
e.Logger().Warnf(`binder: arg error, value %T#%v kind is %v`, m, propPath, value.Kind())
break
}
typev = value.Type()
f, _ = typev.FieldByName(name)
if tagfast.Value(tc, f, `form_options`) == `-` {
break
}
continue
}
//最后一个元素
tv := value.FieldByName(name)
if !tv.IsValid() {
break
}
if !tv.CanSet() {
e.Logger().Warnf(`binder: can not set %v to %v`, k, tv)
break
}
f, _ := typev.FieldByName(name)
if tagfast.Value(tc, f, `form_options`) == `-` {
break
}
if tv.Kind() == reflect.Ptr {
tv.Set(reflect.New(tv.Type().Elem()))
tv = tv.Elem()
}
var l interface{}
switch k := tv.Kind(); k {
case reflect.String:
switch tagfast.Value(tc, f, `form_filter`) {
case `html`:
v = DefaultHTMLFilter(v)
default:
delimter := tagfast.Value(tc, f, `form_delimiter`)
if len(delimter) > 0 {
v = strings.Join(t, delimter)
}
}
l = v
tv.Set(reflect.ValueOf(l))
case reflect.Bool:
l = (v != `false` && v != `0` && v != ``)
tv.Set(reflect.ValueOf(l))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
dateformat := tagfast.Value(tc, f, `form_format`)
if len(dateformat) > 0 {
t, err := time.Parse(dateformat, v)
if err != nil {
e.Logger().Warnf(`binder: arg %v as int: %v`, v, err)
l = int(0)
} else {
l = int(t.Unix())
}
} else {
x, err := strconv.Atoi(v)
if err != nil {
e.Logger().Warnf(`binder: arg %v as int: %v`, v, err)
}
l = x
}
tv.Set(reflect.ValueOf(l))
case reflect.Int64:
dateformat := tagfast.Value(tc, f, `form_format`)
if len(dateformat) > 0 {
t, err := time.Parse(dateformat, v)
if err != nil {
e.Logger().Warnf(`binder: arg %v as int64: %v`, v, err)
l = int64(0)
} else {
l = t.Unix()
}
} else {
x, err := strconv.ParseInt(v, 10, 64)
if err != nil {
e.Logger().Warnf(`binder: arg %v as int64: %v`, v, err)
}
l = x
}
tv.Set(reflect.ValueOf(l))
case reflect.Float32, reflect.Float64:
x, err := strconv.ParseFloat(v, 64)
if err != nil {
e.Logger().Warnf(`binder: arg %v as float64: %v`, v, err)
}
l = x
tv.Set(reflect.ValueOf(l))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
dateformat := tagfast.Value(tc, f, `form_format`)
var x uint64
var bitSize int
switch k {
case reflect.Uint8:
bitSize = 8
case reflect.Uint16:
bitSize = 16
case reflect.Uint32:
bitSize = 32
default:
bitSize = 64
}
if len(dateformat) > 0 {
t, err := time.Parse(dateformat, v)
if err != nil {
e.Logger().Warnf(`binder: arg %v as uint: %v`, v, err)
x = uint64(0)
} else {
x = uint64(t.Unix())
}
} else {
x, err = strconv.ParseUint(v, 10, bitSize)
if err != nil {
e.Logger().Warnf(`binder: arg %v as uint: %v`, v, err)
}
}
switch k {
case reflect.Uint:
l = uint(x)
case reflect.Uint8:
l = uint8(x)
case reflect.Uint16:
l = uint16(x)
case reflect.Uint32:
l = uint32(x)
default:
l = x
}
tv.Set(reflect.ValueOf(l))
case reflect.Struct:
if tvf, ok := tv.Interface().(FromConversion); ok {
err := tvf.FromString(v)
if err != nil {
e.Logger().Warnf(`binder: struct %v invoke FromString faild`, tvf)
}
} else if tv.Type().String() == `time.Time` {
x, err := time.Parse(`2006-01-02 15:04:05.000 -0700`, v)
if err != nil {
x, err = time.Parse(`2006-01-02 15:04:05`, v)
if err != nil {
x, err = time.Parse(`2006-01-02`, v)
if err != nil {
e.Logger().Warnf(`binder: unsupported time format %v, %v`, v, err)
}
}
}
l = x
tv.Set(reflect.ValueOf(l))
} else {
e.Logger().Warn(`binder: can not set an struct which is not implement Fromconversion interface`)
}
case reflect.Ptr:
e.Logger().Warn(`binder: can not set an ptr of ptr`)
case reflect.Slice, reflect.Array:
setSlice(e, name, tv, t)
default:
break
}
//validation
valid := tagfast.Value(tc, f, `valid`)
if len(valid) == 0 {
continue
}
if validator == nil {
validator = validation.New()
}
ok, err := validator.ValidSimple(name, fmt.Sprintf(`%v`, l), valid)
if !ok {
return validator.Errors[0].WithField()
}
if err != nil {
e.Logger().Warn(err)
}
}
}
return nil
}
func setSlice(e *Echo, fieldName string, tv reflect.Value, t []string) {
tt := tv.Type().Elem()
tk := tt.Kind()
if tv.IsNil() {
tv.Set(reflect.MakeSlice(tv.Type(), len(t), len(t)))
}
for i, s := range t {
var err error
switch tk {
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int8, reflect.Int64:
var v int64
v, err = strconv.ParseInt(s, 10, tt.Bits())
if err == nil {
tv.Index(i).SetInt(v)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
var v uint64
v, err = strconv.ParseUint(s, 10, tt.Bits())
if err == nil {
tv.Index(i).SetUint(v)
}
case reflect.Float32, reflect.Float64:
var v float64
v, err = strconv.ParseFloat(s, tt.Bits())
if err == nil {
tv.Index(i).SetFloat(v)
}
case reflect.Bool:
var v bool
v, err = strconv.ParseBool(s)
if err == nil {
tv.Index(i).SetBool(v)
}
case reflect.String:
tv.Index(i).SetString(s)
case reflect.Complex64, reflect.Complex128:
// TODO:
err = fmt.Errorf(`binder: unsupported slice element type %v`, tk.String())
default:
err = fmt.Errorf(`binder: unsupported slice element type %v`, tk.String())
}
if err != nil {
e.Logger().Warnf(`binder: slice error: %v, %v`, fieldName, err)
}
}
}
// FromConversion a struct implements this interface can be convert from request param to a struct
type FromConversion interface {
FromString(content string) error
}
// ToConversion a struct implements this interface can be convert from struct to template variable
// Not Implemented
type ToConversion interface {
ToString() string
}
type (
//FieldNameFormatter 结构体字段值映射到表单时,结构体字段名称格式化处理
FieldNameFormatter func(topName, fieldName string) string
//FormDataFilter 将map映射到结构体时,对名称和值的过滤处理,如果返回的名称为空,则跳过本字段
FormDataFilter func(key string, values []string) (string, []string)
)
var (
//DefaultNopFilter 默认过滤器(map->struct)
DefaultNopFilter FormDataFilter = func(k string, v []string) (string, []string) {
return k, v
}
//DefaultFieldNameFormatter 默认格式化函数(struct->form)
DefaultFieldNameFormatter FieldNameFormatter = func(topName, fieldName string) string {
var fName string
if len(topName) == 0 {
fName = fieldName
} else {
fName = topName + "." + fieldName
}
return fName
}
//LowerCaseFirstLetter 小写首字母(struct->form)
LowerCaseFirstLetter FieldNameFormatter = func(topName, fieldName string) string {
var fName string
s := []rune(fieldName)
if len(s) > 0 {
s[0] = unicode.ToLower(s[0])
fieldName = string(s)
}
if len(topName) == 0 {
fName = fieldName
} else {
fName = topName + "." + fieldName
}
return fName
}
)
//StructToForm 映射struct到form
func StructToForm(ctx Context, m interface{}, topName string, fieldNameFormatter FieldNameFormatter) {
vc := reflect.ValueOf(m)
tc := reflect.TypeOf(m)
switch tc.Kind() {
case reflect.Struct:
case reflect.Ptr:
vc = vc.Elem()
tc = tc.Elem()
}
l := tc.NumField()
f := ctx.Request().Form()
if fieldNameFormatter == nil {
fieldNameFormatter = DefaultFieldNameFormatter
}
for i := 0; i < l; i++ {
fVal := vc.Field(i)
fTyp := tc.Field(i)
fName := fieldNameFormatter(topName, fTyp.Name)
if !fVal.CanInterface() || len(fName) == 0 {
continue
}
switch fTyp.Type.String() {
case "time.Time":
if t, y := fVal.Interface().(time.Time); y {
dateformat := tagfast.Value(tc, fTyp, `form_format`)
if len(dateformat) > 0 {
f.Add(fName, t.Format(dateformat))
} else {
f.Add(fName, t.Format(`2006-01-02 15:04:05`))
}
}
case "struct":
StructToForm(ctx, fVal.Interface(), fName, fieldNameFormatter)
default:
f.Add(fName, fmt.Sprint(fVal.Interface()))
}
}
}