forked from goraz/onion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonion.go
565 lines (481 loc) · 12.9 KB
/
onion.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
package onion
import (
"reflect"
"strconv"
"strings"
"sync"
"time"
)
// DefaultDelimiter is the default delimiter for the config scope
const DefaultDelimiter = "."
// Layer is an interface to handle the load phase.
type Layer interface {
// Load a layer into the Onion. the call is only done in the
// registration
Load() (map[string]interface{}, error)
}
// LazyLayer is the layer for lazy config sources, when the entire configs is not
// available at the registration
type LazyLayer interface {
// Get return the value for this config in this layer, if exists, if not return
// false as the 2nd return value
Get(...string) (interface{}, bool)
}
type singleLayer struct {
layer Layer
lazy LazyLayer
data map[string]interface{}
}
type layerList []singleLayer
type variable struct {
key string
ref interface{}
def interface{}
}
// Onion is a layer base configuration system
type Onion struct {
delimiter string
ll layerList
llock sync.RWMutex
references []variable
refLock sync.RWMutex
}
func (sl singleLayer) getData(d string, path ...string) (interface{}, bool) {
if sl.lazy != nil {
return sl.lazy.Get(path...)
}
return searchStringMap(path, sl.data)
}
// AddLayer add a new layer to the end of config layers. last layer is loaded after all other
// layer
func (o *Onion) AddLayer(l Layer) error {
o.llock.Lock()
defer o.llock.Unlock()
data, err := l.Load()
if err != nil {
return err
}
o.ll = append(
o.ll,
singleLayer{
layer: l,
lazy: nil,
data: lowerStringMap(data),
},
)
return nil
}
// AddLazyLayer add a new lazy layer to the end of config layers. last layer is loaded after
// all other layer
func (o *Onion) AddLazyLayer(l LazyLayer) {
o.llock.Lock()
defer o.llock.Unlock()
o.ll = append(
o.ll,
singleLayer{
layer: nil,
lazy: l,
data: nil,
},
)
}
// GetDelimiter return the delimiter for nested key
func (o *Onion) GetDelimiter() string {
if o.delimiter == "" {
o.delimiter = DefaultDelimiter
}
return o.delimiter
}
// SetDelimiter set the current delimiter
func (o *Onion) SetDelimiter(d string) {
o.delimiter = d
}
// Get try to get the key from config layers
func (o *Onion) Get(key string) (interface{}, bool) {
o.llock.RLock()
defer o.llock.RUnlock()
key = strings.Trim(key, " ")
if len(key) == 0 {
return nil, false
}
path := strings.Split(strings.ToLower(key), o.GetDelimiter())
for i := len(o.ll) - 1; i >= 0; i-- {
res, found := o.ll[i].getData(o.GetDelimiter(), path...)
if found {
return res, found
}
}
return nil, false
}
// The following two function are identical. but converting between map[string] and
// map[interface{}] is not easy, and there is no _Generic_ way to do it, so I decide to create
// two almost identical function instead of writing a converter each time.
//
// Some of the loaders like yaml, load inner keys in map[interface{}]interface{}
// some other like json do it in map[string]interface{} so we should support both
func searchStringMap(path []string, m map[string]interface{}) (interface{}, bool) {
v, ok := m[path[0]]
if !ok {
return nil, false
}
if len(path) == 1 {
return v, true
}
switch m := v.(type) {
case map[string]interface{}:
return searchStringMap(path[1:], m)
case map[interface{}]interface{}:
return searchInterfaceMap(path[1:], m)
}
return nil, false
}
func searchInterfaceMap(path []string, m map[interface{}]interface{}) (interface{}, bool) {
v, ok := m[path[0]]
if !ok {
return nil, false
}
if len(path) == 1 {
return v, true
}
switch m := v.(type) {
case map[string]interface{}:
return searchStringMap(path[1:], m)
case map[interface{}]interface{}:
return searchInterfaceMap(path[1:], m)
}
return nil, false
}
func lowerStringMap(m map[string]interface{}) map[string]interface{} {
res := make(map[string]interface{})
for k := range m {
switch nm := m[k].(type) {
case map[string]interface{}:
res[strings.ToLower(k)] = lowerStringMap(nm)
case map[interface{}]interface{}:
res[strings.ToLower(k)] = lowerInterfaceMap(nm)
default:
res[strings.ToLower(k)] = m[k]
}
}
return res
}
func lowerInterfaceMap(m map[interface{}]interface{}) map[interface{}]interface{} {
res := make(map[interface{}]interface{})
for k := range m {
switch k.(type) {
case string:
switch nm := m[k].(type) {
case map[string]interface{}:
res[strings.ToLower(k.(string))] = lowerStringMap(nm)
case map[interface{}]interface{}:
res[strings.ToLower(k.(string))] = lowerInterfaceMap(nm)
default:
res[strings.ToLower(k.(string))] = m[k]
}
default:
res[k] = m[k]
}
}
return res
}
// GetIntDefault return an int value from Onion, if the value is not exists or its not an
// integer , default is returned
func (o *Onion) GetIntDefault(key string, def int) int {
return int(o.GetInt64Default(key, int64(def)))
}
// GetInt return an int value, if the value is not there, then it return zero value
func (o *Onion) GetInt(key string) int {
return o.GetIntDefault(key, 0)
}
// GetInt64Default return an int64 value from Onion, if the value is not exists or if the value is not
// int64 then return the default
func (o *Onion) GetInt64Default(key string, def int64) int64 {
v, ok := o.Get(key)
if !ok {
return def
}
switch nv := v.(type) {
case string:
// Env is not typed and always is String, so try to convert it to int
// if possible
var i int64
var err error
if strings.HasPrefix(nv, "0x") {
i, err = strconv.ParseInt(nv[2:], 16, 64)
} else if strings.HasPrefix(nv, "0") {
i, err = strconv.ParseInt(nv, 8, 64)
} else {
i, err = strconv.ParseInt(nv, 10, 64)
}
if err != nil {
return def
}
return i
case int:
return int64(nv)
case int64:
return nv
case float32:
return int64(nv)
case float64:
return int64(nv)
default:
return def
}
}
// GetInt64 return the int64 value from config, if its not there, return zero
func (o *Onion) GetInt64(key string) int64 {
return o.GetInt64Default(key, 0)
}
// GetFloat32Default return an float32 value from Onion, if the value is not exists or its not a
// float32, default is returned
func (o *Onion) GetFloat32Default(key string, def float32) float32 {
return float32(o.GetFloat64Default(key, float64(def)))
}
// GetFloat32 return an float32 value, if the value is not there, then it returns zero value
func (o *Onion) GetFloat32(key string) float32 {
return o.GetFloat32Default(key, 0)
}
// GetFloat64Default return an float64 value from Onion, if the value is not exists or if the value is not
// float64 then return the default
func (o *Onion) GetFloat64Default(key string, def float64) float64 {
v, ok := o.Get(key)
if !ok {
return def
}
switch nv := v.(type) {
case string:
// Env is not typed and always is String, so try to convert it to int
// if possible
f, err := strconv.ParseFloat(nv, 64)
if err != nil {
return def
}
return f
case int:
return float64(nv)
case int64:
return float64(nv)
case float32:
return float64(nv)
case float64:
return nv
default:
return def
}
}
// GetFloat64 return the float64 value from config, if its not there, return zero
func (o *Onion) GetFloat64(key string) float64 {
return o.GetFloat64Default(key, 0)
}
// GetStringDefault get a string from Onion. if the value is not exists or if tha value is not
// string, return the default
func (o *Onion) GetStringDefault(key string, def string) string {
v, ok := o.Get(key)
if !ok {
return def
}
s, ok := v.(string)
if !ok {
return def
}
return s
}
// GetString is for getting an string from conig. if the key is not
func (o *Onion) GetString(key string) string {
return o.GetStringDefault(key, "")
}
// GetBoolDefault return bool value from Onion. if the value is not exists or if tha value is not
// boolean, return the default
func (o *Onion) GetBoolDefault(key string, def bool) bool {
v, ok := o.Get(key)
if !ok {
return def
}
switch nv := v.(type) {
case string:
// Env is not typed and always is String, so try to convert it to int
// if possible
i, err := strconv.ParseBool(nv)
if err != nil {
return def
}
return i
case bool:
return nv
default:
return def
}
}
// GetBool is used to get a boolean value fro config, with false as default
func (o *Onion) GetBool(key string) bool {
return o.GetBoolDefault(key, false)
}
// GetDurationDefault is a function to get duration from config. it support both
// string duration (like 1h3m2s) and integer duration
func (o *Onion) GetDurationDefault(key string, def time.Duration) time.Duration {
v, ok := o.Get(key)
if !ok {
return def
}
switch nv := v.(type) {
case string:
d, err := time.ParseDuration(nv)
if err != nil {
return def
}
return d
case int:
return time.Duration(nv)
case int64:
return time.Duration(nv)
case time.Duration:
return nv
default:
return def
}
}
// GetDuration is for getting duration from config, it cast both int and string
// to duration
func (o *Onion) GetDuration(key string) time.Duration {
return o.GetDurationDefault(key, 0)
}
func (o *Onion) getSlice(key string) (interface{}, bool) {
v, ok := o.Get(key)
if !ok {
return nil, false
}
if reflect.TypeOf(v).Kind() != reflect.Slice { // Not good
return nil, false
}
return v, true
}
// GetStringSlice try to get a slice from the config
func (o *Onion) GetStringSlice(key string) []string {
var ok bool
v, ok := o.getSlice(key)
if !ok {
str := o.GetString(key)
if len(str) <= 0 {
return nil
}
v = strings.Split(str, ",")
}
switch nv := v.(type) {
case []string:
return nv
case []interface{}:
res := make([]string, len(nv))
for i := range nv {
if res[i], ok = nv[i].(string); !ok {
return nil
}
}
return res
}
return nil
}
func (o *Onion) addRef(key string, ref interface{}, def interface{}) {
o.refLock.Lock()
defer o.refLock.Unlock()
o.references = append(o.references, variable{key: key, ref: ref, def: def})
}
// RegisterInt return an int variable and set the value when the config is loaded
func (o *Onion) RegisterInt(key string, def int) Int {
var v = int64(def)
o.addRef(key, &v, def)
return intHolder{value: &v}
}
// RegisterInt64 return an int64 variable and set the value when the config is loaded
func (o *Onion) RegisterInt64(key string, def int64) Int {
var v = def
o.addRef(key, &v, def)
return intHolder{value: &v}
}
// RegisterString return an string variable and set the value when the config is loaded
func (o *Onion) RegisterString(key string, def string) String {
var v = def
o.addRef(key, &v, def)
return stringHolder{value: &v}
}
// RegisterFloat64 return an float64 variable and set the value when the config is loaded
func (o *Onion) RegisterFloat64(key string, def float64) Float {
var v = def
o.addRef(key, &v, def)
return floatHolder{value: &v}
}
// RegisterFloat32 return an float32 variable and set the value when the config is loaded
func (o *Onion) RegisterFloat32(key string, def float32) Float {
var v = float64(def)
o.addRef(key, &v, def)
return floatHolder{value: &v}
}
// RegisterBool return an bool variable and set the value when the config is loaded
func (o *Onion) RegisterBool(key string, def bool) Bool {
var v = def
o.addRef(key, &v, def)
return boolHolder{value: &v}
}
// RegisterDuration return an duration variable and set the value when the config is loaded
func (o *Onion) RegisterDuration(key string, def time.Duration) Int {
var v = int64(def)
o.addRef(key, &v, def)
return intHolder{value: &v}
}
// Load function is the new behavior of onion after version 3. after calling this all variables
// registered with Registered* function are loaded.
// this function is concurrent safe.
// also this function had no effect on getting variables directly from config by Get* functions
func (o *Onion) Load() {
o.refLock.RLock()
defer o.refLock.RUnlock()
// Make sure all variables are locked
// TODO : lock per onion instance
globalLock.Lock()
defer globalLock.Unlock()
for i := range o.references {
switch def := o.references[i].def.(type) {
case int:
v := o.GetInt64Default(o.references[i].key, int64(def))
t := o.references[i].ref.(*int64)
*t = v
case int64:
v := o.GetInt64Default(o.references[i].key, def)
t := o.references[i].ref.(*int64)
*t = v
case string:
v := o.GetStringDefault(o.references[i].key, def)
t := o.references[i].ref.(*string)
*t = v
case float32:
v := o.GetFloat64Default(o.references[i].key, float64(def))
t := o.references[i].ref.(*float64)
*t = v
case float64:
v := o.GetFloat64Default(o.references[i].key, def)
t := o.references[i].ref.(*float64)
*t = v
case bool:
v := o.GetBoolDefault(o.references[i].key, def)
t := o.references[i].ref.(*bool)
*t = v
case time.Duration:
v := o.GetDurationDefault(o.references[i].key, def)
t := o.references[i].ref.(*int64)
*t = int64(v)
}
}
}
// Reset clear all layers, but not registered variables
func (o *Onion) Reset() {
o.llock.Lock()
defer o.llock.Unlock()
// Delete al layers
o.ll = nil
}
// New return a new Onion
func New() *Onion {
return &Onion{
delimiter: DefaultDelimiter,
}
}