-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper_string.go
82 lines (69 loc) · 1.8 KB
/
mapper_string.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
package structure
import (
"fmt"
"reflect"
"strconv"
"strings"
)
func init() {
registerMapper(stringType, boolType, string2boolMapper)
registerMapper(stringType, intType, string2intMapper)
registerMapper(stringType, uintType, string2uintMapper)
registerMapper(stringType, float64Type, string2floatMapper)
registerMapper(stringType, stringType, string2stringMapper)
}
func string2boolMapper(from reflect.Value, to reflect.Value, _ *Option) error {
str := strings.TrimSpace(from.String())
b, err := strconv.ParseBool(str)
if err == nil {
to.SetBool(b)
} else if strings.TrimSpace(str) == "" {
to.SetBool(false)
} else {
return fmt.Errorf("cannot parse '%s' as bool: %s", str, err)
}
return nil
}
func string2intMapper(from reflect.Value, to reflect.Value, _ *Option) error {
str := strings.TrimSpace(from.String())
if str == "" {
str = "0"
}
i, err := strconv.ParseInt(str, 0, to.Type().Bits())
if err == nil {
to.SetInt(i)
} else {
return fmt.Errorf("cannot parse '%s' as int: %s", str, err)
}
return nil
}
func string2uintMapper(from reflect.Value, to reflect.Value, _ *Option) error {
str := strings.TrimSpace(from.String())
if str == "" {
str = "0"
}
ui, err := strconv.ParseUint(str, 0, to.Type().Bits())
if err == nil {
to.SetUint(ui)
} else {
return fmt.Errorf("cannot parse '%s' as uint: %s", str, err)
}
return nil
}
func string2floatMapper(from reflect.Value, to reflect.Value, _ *Option) error {
str := strings.TrimSpace(from.String())
if str == "" {
str = "0"
}
f, err := strconv.ParseFloat(str, to.Type().Bits())
if err == nil {
to.SetFloat(f)
} else {
return fmt.Errorf("cannot parse '%s' as float: %s", str, err)
}
return nil
}
func string2stringMapper(from reflect.Value, to reflect.Value, _ *Option) error {
to.SetString(from.String())
return nil
}