-
Notifications
You must be signed in to change notification settings - Fork 921
/
config.go
140 lines (114 loc) · 2.42 KB
/
config.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
package config
import (
"strconv"
"strings"
)
type ConfigSource interface {
GetValue(key string) interface{}
Name() string
}
type ConfigOption struct {
Name string
Description string
DefaultValue interface{}
LoadedValue interface{}
Manager *ConfigManager
ConfigSource ConfigSource
}
func (opt *ConfigOption) LoadValue() {
newVal := opt.DefaultValue
opt.ConfigSource = nil
for i := len(opt.Manager.sources) - 1; i >= 0; i-- {
source := opt.Manager.sources[i]
v := source.GetValue(opt.Name)
if v != nil {
newVal = v
opt.ConfigSource = source
break
}
}
// parse ahead of time
if opt.DefaultValue != nil {
if _, ok := opt.DefaultValue.(int); ok {
newVal = interface{}(intVal(newVal))
} else if _, ok := opt.DefaultValue.(bool); ok {
newVal = interface{}(boolVal(newVal))
}
}
opt.LoadedValue = newVal
}
func (opt *ConfigOption) GetString() string {
return strVal(opt.LoadedValue)
}
func (opt *ConfigOption) GetInt() int {
return intVal(opt.LoadedValue)
}
func (opt *ConfigOption) GetBool() bool {
return boolVal(opt.LoadedValue)
}
type ConfigManager struct {
sources []ConfigSource
Options map[string]*ConfigOption
}
func NewConfigManager() *ConfigManager {
return &ConfigManager{
Options: make(map[string]*ConfigOption),
}
}
func (c *ConfigManager) AddSource(source ConfigSource) {
c.sources = append(c.sources, source)
}
func (c *ConfigManager) RegisterOption(name, desc string, defaultValue interface{}) *ConfigOption {
opt := &ConfigOption{
Name: name,
Description: desc,
DefaultValue: defaultValue,
Manager: c,
}
c.Options[name] = opt
return opt
}
func (c *ConfigManager) Load() {
for _, v := range c.Options {
v.LoadValue()
}
}
func strVal(i interface{}) string {
switch t := i.(type) {
case string:
return t
case int:
return strconv.FormatInt(int64(t), 10)
case Stringer:
return t.String()
}
return ""
}
type Stringer interface {
String() string
}
func intVal(i interface{}) int {
switch t := i.(type) {
case string:
n, _ := strconv.ParseInt(t, 10, 64)
return int(n)
case int:
return t
}
return 0
}
func boolVal(i interface{}) bool {
switch t := i.(type) {
case string:
lower := strings.ToLower(strings.TrimSpace(t))
if lower == "true" || lower == "yes" || lower == "on" || lower == "enabled" || lower == "1" {
return true
}
return false
case int:
return t > 0
case bool:
return t
}
return false
}