-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.go
74 lines (60 loc) · 1.47 KB
/
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
package config
import (
"fmt"
"reflect"
"regexp"
"strconv"
)
var stringType = reflect.TypeOf("")
type stringSetter struct {
val *string
tag reflect.StructTag
}
func (ss *stringSetter) String() string {
if ss.val == nil {
return ""
}
return *ss.val
}
func (ss *stringSetter) Set(val string) error {
if tag := ss.tag.Get("regexp"); tag != "" {
r, err := regexp.Compile(tag)
if err != nil {
return &ValidationError{Value: val, Message: err.Error()}
}
if !r.MatchString(val) {
msg := fmt.Sprintf("'%s' did not match regular expression '%s'", val, r)
return &ValidationError{Value: val, Message: msg}
}
}
*ss.val = val
return nil
}
func (ss *stringSetter) SetInt(val int64) error {
return ss.Set(strconv.FormatInt(val, 10))
}
func (ss *stringSetter) SetUint(val uint64) error {
return ss.Set(strconv.FormatUint(val, 10))
}
func (ss *stringSetter) SetFloat(val float64) error {
return ss.Set(strconv.FormatFloat(val, 'f', -1, 64))
}
func (ss *stringSetter) SetBool(val bool) error {
return ss.Set(strconv.FormatBool(val))
}
func (ss *stringSetter) Get() interface{} {
if ss.val == nil {
return ""
}
return *ss.val
}
type stringSetterCreator struct{}
func (ssc stringSetterCreator) Type() reflect.Type {
return stringType
}
func (ssc stringSetterCreator) Setter(val reflect.Value, tag reflect.StructTag) Setter {
return &stringSetter{val: val.Addr().Interface().(*string), tag: tag}
}
func init() {
DefaultSetterRegistry.Add(stringSetterCreator{})
}