-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtype_field.go
127 lines (110 loc) · 2.44 KB
/
type_field.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
package envconf
import (
"errors"
"fmt"
"reflect"
"github.com/antonmashko/envconf/external"
"github.com/antonmashko/envconf/option"
)
type fieldType struct {
*configField
v reflect.Value
sf reflect.StructField
}
func newFieldType(v reflect.Value, s *configField) *fieldType {
return &fieldType{
configField: s,
v: v,
}
}
func (*fieldType) externalSource() external.ExternalSource {
return external.NilContainer{}
}
func (f *fieldType) init() error {
return f.configField.init(f)
}
func (f *fieldType) define() error {
v, cs := f.configField.Value()
if cs == option.NoConfigValue {
return ErrConfigurationNotFound
}
if cs == option.ExternalSource {
// field should be defined through External.Unmarshal func
return f.set(v, cs)
}
str, ok := v.(string)
if !ok {
return &Error{
Inner: ErrUnsupportedType,
FieldName: f.fullName(),
Message: "v is not string",
}
}
if !f.v.CanSet() {
return &Error{
Inner: errors.New("reflect: cannot set"),
FieldName: f.fullName(),
}
}
var err error
v, err = setFromString(f.v, str)
if err != nil {
return &Error{
Inner: fmt.Errorf("type=%s source=%s. %w", f.sf.Type, cs, err),
FieldName: f.fullName(),
Message: "cannot set",
}
}
return f.set(v, cs)
}
type interfaceFieldType struct {
*fieldType
}
func (f *interfaceFieldType) define() error {
v, cs := f.Value()
if cs == option.NoConfigValue {
return ErrConfigurationNotFound
}
if cs == option.ExternalSource {
// field should be defined through External.Unmarshal func
return f.set(v, cs)
}
rv := reflect.ValueOf(v)
if !rv.Type().AssignableTo(f.v.Type()) {
return &Error{
FieldName: f.fullName(),
Message: fmt.Sprintf("unable to assign type %s to %s", rv.Type(), f.sf.Type),
}
}
f.v.Set(rv)
return f.set(v, cs)
}
type customSetFieldType struct {
*fieldType
}
func (f *customSetFieldType) define() error {
v, cs := f.Value()
if cs == option.NoConfigValue {
return ErrConfigurationNotFound
}
if cs == option.ExternalSource {
// field should be defined through External.Unmarshal func
return f.set(v, cs)
}
str, ok := v.(string)
if !ok {
return &Error{
Inner: ErrUnsupportedType,
FieldName: f.fullName(),
Message: "v is not string",
}
}
implF := asImpl(f.v)
if implF == nil {
return errors.New("setter not found")
}
if err := implF([]byte(str)); err != nil {
return &Error{Inner: err, FieldName: f.fullName()}
}
return f.set(v, cs)
}