-
Notifications
You must be signed in to change notification settings - Fork 4
/
bind.go
268 lines (240 loc) · 5.99 KB
/
bind.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
package registry
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
)
var errInvalidValue = errors.New("Invalid value")
var (
tags = []string{"default", "env", "flag", "registry"}
)
type config struct {
rawConfig sync.Locker
ident string
items []item
}
func (r *registry) Bind(i sync.Locker) error {
cfg := config{
rawConfig: i,
ident: fmt.Sprintf("%s.%d", reflect.TypeOf(i).Elem().Name(), len(r.configs)+1),
}
err := cfg.bind(i, ``)
if err != nil {
return err
}
r.configs = append(r.configs, cfg)
if r.refreshInterval != -1 {
r.bindChan <- struct{}{}
}
return nil
}
func (cfg *config) callOnUpdatedMethod(updatedItemKeys []string) {
for _, key := range updatedItemKeys {
methodValue := reflect.ValueOf(cfg.rawConfig).MethodByName("OnUpdate" + key)
if !methodValue.IsValid() {
continue
}
methodValue.Call([]reflect.Value{})
}
}
type item struct {
key string // registry key
path string // field path (SomeField.AnotherField.LeafField -> "SomeFieldAnotherFieldLeafField")
reference reflect.Value
}
var typeOfDuration = reflect.TypeOf(time.Duration(0))
func (i *item) equal(value interface{}) bool {
return reflect.DeepEqual(i.reference.Interface(), value)
}
func (i *item) set(rawValue string) error {
if len(rawValue) == 0 {
return nil
}
var (
err error
defaultValue interface{}
)
switch i.reference.Type() {
case typeOfDuration:
defaultValue, err = time.ParseDuration(rawValue)
default:
defaultValue, err = defaultByKind(i.reference.Type(), rawValue)
}
if err != nil {
return err
}
if i.reference.CanSet() && defaultValue != nil {
i.reference.Set(reflect.ValueOf(defaultValue))
}
return nil
}
func defaultByKind(tp reflect.Type, rawValue string) (defaultValue interface{}, err error) {
switch tp.Kind() {
case reflect.String:
defaultValue = rawValue
case reflect.Int:
if defaultValue, err = strconv.ParseInt(rawValue, 10, 0); err == nil {
defaultValue = int(defaultValue.(int64))
}
case reflect.Int8:
if defaultValue, err = strconv.ParseInt(rawValue, 10, 8); err == nil {
defaultValue = int8(defaultValue.(int64))
}
case reflect.Int16:
if defaultValue, err = strconv.ParseInt(rawValue, 10, 16); err == nil {
defaultValue = int16(defaultValue.(int64))
}
case reflect.Int32:
if defaultValue, err = strconv.ParseInt(rawValue, 10, 32); err == nil {
defaultValue = int32(defaultValue.(int64))
}
case reflect.Int64:
defaultValue, err = strconv.ParseInt(rawValue, 10, 64)
case reflect.Uint:
if defaultValue, err = strconv.ParseUint(rawValue, 10, 0); err == nil {
defaultValue = uint(defaultValue.(uint64))
}
case reflect.Uint8:
if defaultValue, err = strconv.ParseUint(rawValue, 10, 8); err == nil {
defaultValue = uint8(defaultValue.(uint64))
}
case reflect.Uint16:
if defaultValue, err = strconv.ParseUint(rawValue, 10, 16); err == nil {
defaultValue = uint16(defaultValue.(uint64))
}
case reflect.Uint32:
if defaultValue, err = strconv.ParseUint(rawValue, 10, 32); err == nil {
defaultValue = uint32(defaultValue.(uint64))
}
case reflect.Uint64:
defaultValue, err = strconv.ParseUint(rawValue, 10, 64)
case reflect.Float32:
if defaultValue, err = strconv.ParseFloat(rawValue, 10); err == nil {
defaultValue = float32(defaultValue.(float64))
}
case reflect.Float64:
defaultValue, err = strconv.ParseFloat(rawValue, 10)
case reflect.Bool:
defaultValue, err = strconv.ParseBool(rawValue)
case reflect.Slice:
values := strings.Split(rawValue, ",")
rslice := reflect.MakeSlice(tp, len(values), cap(values))
if len(values) > 0 {
fieldType := rslice.Index(0).Type()
for i, v := range values {
r, err := defaultByKind(fieldType, v)
if err != nil {
break
}
rval := reflect.ValueOf(r)
if !rval.IsValid() {
break
}
rslice.Index(i).Set(rval)
}
}
defaultValue = rslice.Interface()
}
return
}
func (cfg *config) bind(i interface{}, prefix string) error {
var (
rt = reflect.TypeOf(i)
rv = reflect.ValueOf(i)
)
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
rv = rv.Elem()
}
var fields []string
for i := 0; i < rt.NumField(); i++ {
var (
field = rt.Field(i)
value = rv.FieldByName(field.Name)
fieldPath = prefix + field.Name
)
if len(field.PkgPath) != 0 { // enexported
continue
}
switch field.Type.Kind() {
case reflect.Struct:
err := cfg.bind(value.Addr().Interface(), fieldPath)
if err != nil {
return fmt.Errorf("'%s': %v", field.Name, err)
}
default:
item, err := makeItem(field, fieldPath, value)
if err != nil {
return fmt.Errorf("'%s': %v", field.Name, err)
}
if len(item.key) != 0 {
cfg.items = append(cfg.items, item)
}
fields = append(fields, fieldPath)
}
}
cfg.callOnUpdatedMethod(fields) // Call method "OnUpdate<variableName>" if exists
return nil
}
func makeItem(field reflect.StructField, path string, value reflect.Value) (item, error) {
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
if !value.IsValid() {
return item{}, errInvalidValue
}
var (
tagValue string
rawValue string
registryKey string
)
for _, key := range tags {
tagValue = field.Tag.Get(key)
switch key {
case "registry":
registryKey = tagValue
case "default":
rawValue = tagValue
case "env":
if value := os.Getenv(tagValue); len(value) != 0 {
rawValue = value
}
case "flag":
if len(tagValue) != 0 {
if value := flag(tagValue); len(value) != 0 {
rawValue = value
}
}
}
}
new := item{key: registryKey, reference: value, path: path}
if err := new.set(rawValue); err != nil {
return item{}, err
}
return new, nil
}
func flag(name string) string {
prefix := "--"
if len(name) == 1 {
prefix = "-"
}
name = prefix + name
for i, arg := range args {
if strings.Contains(arg, "=") && strings.HasPrefix(arg, name) {
if parts := strings.Split(arg, "="); len(parts) == 2 {
return parts[1]
}
}
if arg == name {
if len(args) >= i {
return args[i+1]
}
}
}
return ""
}