-
Notifications
You must be signed in to change notification settings - Fork 1
/
binder.go
801 lines (730 loc) · 20.8 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// Package binder is Parameter Binding Verification Plugin for Struct Handler.
//
// Copyright 2018 HenryLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package binder
import (
"errors"
"fmt"
"math"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/henrylee2cn/goutil"
tp "github.com/henrylee2cn/teleport"
)
/**
Parameter Binding Verification Plugin for Struct Handler.
- Param-Tags
tag | key | required | value | desc
------|----------|----------|---------------|----------------------------------
param | query | no | (name e.g.`id`) | It indicates that the parameter is from the URI query part. e.g. `/a/b?x={query}`
param | swap | no | (name e.g.`id`) | It indicates that the parameter is from the context swap.
param | desc | no | (e.g.`id`) | Parameter Description
param | len | no | (e.g.`3:6`) | Length range [a,b] of parameter's value
param | range | no | (e.g.`0:10`) | Numerical range [a,b] of parameter's value
param | nonzero | no | - | Not allowed to zero
param | regexp | no | (e.g.`^\w+$`) | Regular expression validation
param | rerr | no |(e.g.`100002:wrong password format`)| Custom error code and message
NOTES:
* `param:"-"` means ignore
* Encountered untagged exportable anonymous structure field, automatic recursive resolution
* Parameter name is the name of the structure field converted to snake format
* If the parameter is not from `query` or `swap`, it is the default from the body
- Field-Types
base | slice | special
--------|------------|------------
string | []string | [][]byte
byte | []byte | [][]uint8
uint8 | []uint8 | struct
bool | []bool |
int | []int |
int8 | []int8 |
int16 | []int16 |
int32 | []int32 |
int64 | []int64 |
uint8 | []uint8 |
uint16 | []uint16 |
uint32 | []uint32 |
uint64 | []uint64 |
float32 | []float32 |
float64 | []float64 |
*/
type (
// StructArgsBinder a plugin that binds and validates structure type parameters.
StructArgsBinder struct {
binders map[string]*Params
errFunc ErrorFunc
}
// ErrorFunc creates an relational error.
ErrorFunc func(handlerName, paramName, reason string) *tp.Rerror
)
var (
_ tp.PostRegPlugin = new(StructArgsBinder)
_ tp.PostReadCallBodyPlugin = new(StructArgsBinder)
)
// NewStructArgsBinder creates a plugin that binds and validates structure type parameters.
func NewStructArgsBinder(fn ErrorFunc) *StructArgsBinder {
s := &StructArgsBinder{
binders: make(map[string]*Params),
errFunc: fn,
}
s.SetErrorFunc(fn)
return s
}
var (
_ tp.PostRegPlugin = new(StructArgsBinder)
_ tp.PostReadCallBodyPlugin = new(StructArgsBinder)
)
// SetErrorFunc sets the binding or balidating error function.
// Note: If fn=nil, set as default.
func (s *StructArgsBinder) SetErrorFunc(fn ErrorFunc) {
if fn != nil {
s.errFunc = fn
return
}
s.errFunc = func(handlerName, paramName, reason string) *tp.Rerror {
return tp.NewRerror(
tp.CodeBadMessage,
"Invalid Parameter",
fmt.Sprintf(`{"handler": %q, "param": %q, "reason": %q}`, handlerName, paramName, reason),
)
}
}
// Name returns the plugin name.
func (*StructArgsBinder) Name() string {
return "StructArgsBinder"
}
// PostReg preprocessing struct handler.
func (s *StructArgsBinder) PostReg(h *tp.Handler) error {
if h.ArgElemType().Kind() != reflect.Struct {
return nil
}
params := newParams(h.Name(), s)
err := params.addFields([]int{}, h.ArgElemType(), h.NewArgValue().Elem())
if err != nil {
tp.Fatalf("%v", err)
}
s.binders[h.Name()] = params
return nil
}
// PostReadCallBody binds and validates the registered struct handler.
func (s *StructArgsBinder) PostReadCallBody(ctx tp.ReadCtx) *tp.Rerror {
params, ok := s.binders[ctx.Path()]
if !ok {
return nil
}
bodyValue := reflect.ValueOf(ctx.Input().Body())
rerr := params.bindAndValidate(bodyValue, ctx.Query(), ctx.Swap())
if rerr != nil {
return rerr
}
return nil
}
// Params struct handler information for binding and validation
type Params struct {
handlerName string
params []*Param
binder *StructArgsBinder
}
// struct binder parameters'tag
const (
TAG_PARAM = "param" // request param tag name
TAG_IGNORE_PARAM = "-" // ignore request param tag value
KEY_QUERY = "query" // query param(optional), value means parameter(optional)
KEY_SWAP = "swap" // swap param from the context swap(ctx.Swap()) (optional), value means parameter(optional)
KEY_DESC = "desc" // request param description
KEY_LEN = "len" // length range of param's value
KEY_RANGE = "range" // numerical range of param's value
KEY_NONZERO = "nonzero" // param`s value can not be zero
KEY_REGEXP = "regexp" // verify the value of the param with a regular expression(param value can not be null)
KEY_RERR = "rerr" // the custom error code and message for binding or validating
)
func newParams(handlerName string, binder *StructArgsBinder) *Params {
return &Params{
handlerName: handlerName,
params: make([]*Param, 0),
binder: binder,
}
}
func (p *Params) addFields(parentIndexPath []int, t reflect.Type, v reflect.Value) error {
var err error
var deep = len(parentIndexPath) + 1
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
for i := 0; i < t.NumField(); i++ {
indexPath := make([]int, deep)
copy(indexPath, parentIndexPath)
indexPath[deep-1] = i
var field = t.Field(i)
var value = v.Field(i)
canSet := v.Field(i).CanSet()
tag, ok := field.Tag.Lookup(TAG_PARAM)
if !ok {
if canSet && field.Anonymous {
if field.Type.Kind() == reflect.Struct {
if err = p.addFields(indexPath, field.Type, value); err != nil {
return err
}
} else {
return fmt.Errorf("%s.%s anonymous field can only be struct type", t.String(), field.Name)
}
}
continue
}
if tag == TAG_IGNORE_PARAM {
continue
}
if !canSet {
return fmt.Errorf("%s.%s can not be a non-settable field", t.String(), field.Name)
}
if field.Type.Kind() == reflect.Ptr {
return fmt.Errorf("%s.%s can not be a pointer field", t.String(), field.Name)
}
var parsedTags = parseTags(tag)
var paramTypeString = field.Type.String()
var kind = field.Type.Kind()
if _, ok := parsedTags[KEY_LEN]; ok {
if kind != reflect.String && kind != reflect.Slice && kind != reflect.Map && kind != reflect.Array {
return fmt.Errorf("%s.%s invalid `len` tag for field value", t.String(), field.Name)
}
}
if _, ok := parsedTags[KEY_RANGE]; ok {
switch paramTypeString {
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64":
case "[]int", "[]int8", "[]int16", "[]int32", "[]int64", "[]uint", "[]uint8", "[]uint16", "[]uint32", "[]uint64", "[]float32", "[]float64":
default:
return fmt.Errorf("%s.%s invalid `range` tag for non-number field", t.String(), field.Name)
}
}
if _, ok := parsedTags[KEY_REGEXP]; ok {
if paramTypeString != "string" && paramTypeString != "[]string" {
return fmt.Errorf("%s.%s invalid `regexp` tag for non-string field", t.String(), field.Name)
}
}
fd := &Param{
handlerName: p.handlerName,
indexPath: indexPath,
tags: parsedTags,
rawTag: field.Tag,
rawValue: value,
binder: p.binder,
}
rerrTag, ok := fd.tags[KEY_RERR]
if ok {
idx := strings.Index(rerrTag, ":")
if idx != -1 {
if codeStr := strings.TrimSpace(rerrTag[:idx]); len(codeStr) > 0 {
rerrCode, err := strconv.Atoi(codeStr)
if err == nil {
fd.rerrCode = int32(rerrCode)
} else {
return fmt.Errorf("%s.%s invalid `rerr` tag (correct example: `<rerr: 100001: Invalid Parameter>`)", t.String(), field.Name)
}
}
fd.rerrMsg = strings.TrimSpace(rerrTag[idx+1:])
} else {
return fmt.Errorf("%s.%s invalid `rerr` tag (correct example: `<rerr: 100001: Invalid Parameter>`)", t.String(), field.Name)
}
}
if fd.name, ok = parsedTags[KEY_QUERY]; ok {
fd.position = KEY_QUERY
} else if fd.name, ok = parsedTags[KEY_SWAP]; ok {
fd.position = KEY_SWAP
}
if fd.name == "" {
fd.name = goutil.SnakeString(field.Name)
}
if err = fd.makeVerifyFuncs(); err != nil {
return fmt.Errorf("%s.%s invalid validation failed: %s", t.String(), field.Name, err.Error())
}
p.params = append(p.params, fd)
}
return nil
}
func (p *Params) fieldsForBinding(structElem reflect.Value) []reflect.Value {
count := len(p.params)
fields := make([]reflect.Value, count)
for i := 0; i < count; i++ {
value := structElem
param := p.params[i]
for _, index := range param.indexPath {
value = value.Field(index)
}
fields[i] = value
}
return fields
}
func (p *Params) bindAndValidate(structValue reflect.Value, queryValues url.Values, swap goutil.Map) (rerr *tp.Rerror) {
defer func() {
if r := recover(); r != nil {
rerr = p.binder.errFunc(p.handlerName, "", fmt.Sprint(r))
}
}()
var (
err error
fields = p.fieldsForBinding(reflect.Indirect(structValue))
)
for i, param := range p.params {
value := fields[i]
// bind query or swap param
switch param.position {
case KEY_QUERY:
paramValues, ok := queryValues[param.name]
if ok {
if err = convertAssign(value, paramValues); err != nil {
return param.fixRerror(p.binder.errFunc(param.handlerName, param.name, err.Error()))
}
}
case KEY_SWAP:
paramValue, ok := swap.Load(param.name)
if ok {
value = reflect.Indirect(value)
canSet := value.CanSet()
var srcValue reflect.Value
if canSet {
srcValue = reflect.Indirect(reflect.ValueOf(paramValue))
destType := value.Type()
srcType := srcValue.Type()
canSet = srcType.AssignableTo(destType)
if !canSet {
if srcType.ConvertibleTo(destType) {
srcValue = srcValue.Convert(destType)
canSet = srcValue.Type().AssignableTo(destType)
}
}
}
if !canSet {
return param.fixRerror(p.binder.errFunc(
param.handlerName,
param.name,
value.Type().Name()+" can not be setted"),
)
}
value.Set(srcValue)
}
}
if rerr = param.validate(value); rerr != nil {
return rerr
}
}
return
}
// parseTags returns the key-value in the tag string.
// If the tag does not have the conventional format,
// the value returned by parseTags is unspecified.
func parseTags(tag string) map[string]string {
var values = map[string]string{}
for tag != "" {
// Skip leading space.
i := 0
for i < len(tag) && tag[i] != '<' {
i++
}
if i >= len(tag) || tag[i] != '<' {
break
}
i++
// Skip the left Spaces
for i < len(tag) && tag[i] == ' ' {
i++
}
if i >= len(tag) {
break
}
tag = tag[i:]
if tag == "" {
break
}
var name, value string
var hadName bool
i = 0
PAIR:
for i < len(tag) {
switch tag[i] {
case ':':
if hadName {
i++
continue
}
name = strings.TrimRight(tag[:i], " ")
tag = strings.TrimLeft(tag[i+1:], " ")
hadName = true
i = 0
case '\\':
i++
// Fix the escape character of `\\<` or `\\>`
if tag[i] == '<' || tag[i] == '>' {
tag = tag[:i-1] + tag[i:]
} else {
i++
}
case '>':
if !hadName {
name = strings.TrimRight(tag[:i], " ")
} else {
value = strings.TrimRight(tag[:i], " ")
}
values[name] = value
break PAIR
default:
i++
}
}
if i >= len(tag) {
break
}
tag = tag[i+1:]
}
return values
}
// Param use the struct field to define a request parameter model
type Param struct {
handlerName string // handler name
name string // param name
indexPath []int
position string // param position
tags map[string]string // struct tags for this param
verifyFuncs []func(reflect.Value) error
rawTag reflect.StructTag // the raw tag
rawValue reflect.Value // the raw tag value
rerrCode int32 // the custom error code for binding or validating
rerrMsg string // the custom error message for binding or validating
binder *StructArgsBinder
}
const (
stringTypeString = "string"
bytesTypeString = "[]byte"
bytes2TypeString = "[]uint8"
)
// Raw gets the param's original value
func (param *Param) Raw() interface{} {
return param.rawValue.Interface()
}
// Name gets parameter field name
func (param *Param) Name() string {
return param.name
}
// Description gets the description value for the param
func (param *Param) Description() string {
return param.tags[KEY_DESC]
}
// validate tests if the param conforms to it's validation constraints specified
// int the KEY_REGEXP struct tag
func (param *Param) validate(value reflect.Value) (rerr *tp.Rerror) {
defer func() {
if r := recover(); r != nil {
rerr = param.fixRerror(param.binder.errFunc(param.handlerName, param.name, fmt.Sprint(r)))
}
}()
var err error
for _, fn := range param.verifyFuncs {
if err = fn(value); err != nil {
return param.fixRerror(param.binder.errFunc(param.handlerName, param.name, err.Error()))
}
}
return nil
}
func (param *Param) makeVerifyFuncs() (err error) {
defer func() {
p := recover()
if p != nil {
err = fmt.Errorf("%v", p)
}
}()
// length
if tuple, ok := param.tags[KEY_LEN]; ok {
if fn, err := validateLen(tuple); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// range
if tuple, ok := param.tags[KEY_RANGE]; ok {
if fn, err := validateRange(tuple); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// nonzero
if _, ok := param.tags[KEY_NONZERO]; ok {
if fn, err := validateNonZero(); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
// regexp
if reg, ok := param.tags[KEY_REGEXP]; ok {
var isStrings = param.rawValue.Kind() == reflect.Slice
if fn, err := validateRegexp(isStrings, reg); err == nil {
param.verifyFuncs = append(param.verifyFuncs, fn)
} else {
return err
}
}
return
}
func parseTuple(tuple string) (string, string) {
c := strings.Split(tuple, ":")
var a, b string
switch len(c) {
case 1:
a = c[0]
if len(a) > 0 {
return a, a
}
case 2:
a = c[0]
b = c[1]
if len(a) > 0 || len(b) > 0 {
return a, b
}
}
panic("invalid validation tuple")
}
func validateNonZero() (func(value reflect.Value) error, error) {
return func(value reflect.Value) error {
obj := value.Interface()
if obj == reflect.Zero(value.Type()).Interface() {
return errors.New("zero value")
}
return nil
}, nil
}
func validateLen(tuple string) (func(value reflect.Value) error, error) {
var a, b = parseTuple(tuple)
var min, max int
var err error
if len(a) > 0 {
min, err = strconv.Atoi(a)
if err != nil {
return nil, err
}
}
if len(b) > 0 {
max, err = strconv.Atoi(b)
if err != nil {
return nil, err
}
}
return func(value reflect.Value) error {
length := value.Len()
if len(a) > 0 {
if length < min {
return fmt.Errorf("shorter than %s: %v", a, value.Interface())
}
}
if len(b) > 0 {
if length > max {
return fmt.Errorf("longer than %s: %v", b, value.Interface())
}
}
return nil
}, nil
}
const accuracy = 0.0000001
func validateRange(tuple string) (func(value reflect.Value) error, error) {
var a, b = parseTuple(tuple)
var min, max float64
var err error
if len(a) > 0 {
min, err = strconv.ParseFloat(a, 64)
if err != nil {
return nil, err
}
}
if len(b) > 0 {
max, err = strconv.ParseFloat(b, 64)
if err != nil {
return nil, err
}
}
return func(value reflect.Value) error {
var f64 float64
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f64 = float64(value.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
f64 = float64(value.Uint())
case reflect.Float32, reflect.Float64:
f64 = value.Float()
}
if len(a) > 0 {
if math.Min(f64, min) == f64 && math.Abs(f64-min) > accuracy {
return fmt.Errorf("smaller than %s: %v", a, value.Interface())
}
}
if len(b) > 0 {
if math.Max(f64, max) == f64 && math.Abs(f64-max) > accuracy {
return fmt.Errorf("bigger than %s: %v", b, value.Interface())
}
}
return nil
}, nil
}
func validateRegexp(isStrings bool, reg string) (func(value reflect.Value) error, error) {
re, err := regexp.Compile(reg)
if err != nil {
return nil, err
}
if !isStrings {
return func(value reflect.Value) error {
s := value.String()
if !re.MatchString(s) {
return fmt.Errorf("not match %s: %s", reg, s)
}
return nil
}, nil
} else {
return func(value reflect.Value) error {
for _, s := range value.Interface().([]string) {
if !re.MatchString(s) {
return fmt.Errorf("not match %s: %s", reg, s)
}
}
return nil
}, nil
}
}
func (param *Param) fixRerror(rerr *tp.Rerror) *tp.Rerror {
if param.rerrMsg != "" {
rerr.SetMessage(param.rerrMsg)
}
if param.rerrCode != 0 {
rerr.Code = param.rerrCode
}
return rerr
}
func convertAssign(dest reflect.Value, src []string) (err error) {
if len(src) == 0 {
return nil
}
dest = reflect.Indirect(dest)
if !dest.CanSet() {
return fmt.Errorf("%s can not be setted", dest.Type().Name())
}
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("%v", p)
}
}()
switch dest.Interface().(type) {
case string:
dest.Set(reflect.ValueOf(src[0]))
return nil
case []string:
dest.Set(reflect.ValueOf(src))
return nil
case []byte:
dest.Set(reflect.ValueOf([]byte(src[0])))
return nil
case [][]byte:
b := make([][]byte, 0, len(src))
for _, s := range src {
b = append(b, []byte(s))
}
dest.Set(reflect.ValueOf(b))
return nil
case bool:
dest.Set(reflect.ValueOf(parseBool(src[0])))
return nil
case []bool:
b := make([]bool, 0, len(src))
for _, s := range src {
b = append(b, parseBool(s))
}
dest.Set(reflect.ValueOf(b))
return nil
}
switch dest.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i64, err := strconv.ParseInt(src[0], 10, dest.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, src[0], dest.Kind(), err)
}
dest.SetInt(i64)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u64, err := strconv.ParseUint(src[0], 10, dest.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, src[0], dest.Kind(), err)
}
dest.SetUint(u64)
return nil
case reflect.Float32, reflect.Float64:
f64, err := strconv.ParseFloat(src[0], dest.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, src[0], dest.Kind(), err)
}
dest.SetFloat(f64)
return nil
case reflect.Slice:
member := dest.Type().Elem()
switch member.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
for _, s := range src {
i64, err := strconv.ParseInt(s, 10, member.Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, s, dest.Kind(), err)
}
dest.Set(reflect.Append(dest, reflect.ValueOf(i64).Convert(member)))
}
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
for _, s := range src {
u64, err := strconv.ParseUint(s, 10, member.Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, s, dest.Kind(), err)
}
dest.Set(reflect.Append(dest, reflect.ValueOf(u64).Convert(member)))
}
return nil
case reflect.Float32, reflect.Float64:
for _, s := range src {
f64, err := strconv.ParseFloat(s, member.Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting type %T (%q) to a %s: %v", src, s, dest.Kind(), err)
}
dest.Set(reflect.Append(dest, reflect.ValueOf(f64).Convert(member)))
}
return nil
}
}
return fmt.Errorf("unsupported storing type %T into type %s", src, dest.Kind())
}
func parseBool(val string) bool {
switch strings.TrimSpace(strings.ToLower(val)) {
case "true", "on", "1":
return true
}
return false
}
func strconvErr(err error) error {
if ne, ok := err.(*strconv.NumError); ok {
return ne.Err
}
return err
}