forked from koding/multiconfig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiconfig.go
229 lines (196 loc) · 5.46 KB
/
multiconfig.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
package multiconfig
import (
"flag"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/fatih/structs"
)
// Loader loads the configuration from a source. The implementer of Loader is
// responsible for setting the default values of the struct.
type Loader interface {
// Load loads the source into the config defined by struct s
Load(s interface{}) error
}
// DefaultLoader implements the Loader interface. It initializes the given
// pointer of struct s with configuration from the default sources. The order
// of load is TagLoader, FileLoader, EnvLoader and lastly FlagLoader. An error
// in any step stops the loading process. Each step overrides the previous
// step's config (i.e: defining a flag will override previous environment or
// file config). To customize the order use the individual load functions.
type DefaultLoader struct {
Loader
Validator
}
// NewWithPath returns a new instance of Loader to read from the given
// configuration file.
func NewWithPath(path string) *DefaultLoader {
loaders := []Loader{}
// Read default values defined via tag fields "default"
loaders = append(loaders, &TagLoader{})
// Choose what while is passed
if strings.HasSuffix(path, "toml") {
loaders = append(loaders, &TOMLLoader{Path: path})
}
if strings.HasSuffix(path, "json") {
loaders = append(loaders, &JSONLoader{Path: path})
}
if strings.HasSuffix(path, "yml") || strings.HasSuffix(path, "yaml") {
loaders = append(loaders, &YAMLLoader{Path: path})
}
e := &EnvironmentLoader{}
// FlagLoader is unusable right now, refer to: https://github.com/koding/multiconfig/issues/75
// f := &FlagLoader{}
// loaders = append(loaders, e, f)
loaders = append(loaders, e)
loader := MultiLoader(loaders...)
d := &DefaultLoader{}
d.Loader = loader
d.Validator = MultiValidator(&RequiredValidator{})
return d
}
// New returns a new instance of DefaultLoader without any file loaders.
func New() *DefaultLoader {
loader := MultiLoader(
&TagLoader{},
&EnvironmentLoader{},
&FlagLoader{},
)
d := &DefaultLoader{}
d.Loader = loader
d.Validator = MultiValidator(&RequiredValidator{})
return d
}
// MustLoadWithPath loads with the DefaultLoader settings and from the given
// Path. It exits if the config cannot be parsed.
func MustLoadWithPath(path string, conf interface{}) {
d := NewWithPath(path)
d.MustLoad(conf)
}
// MustLoad loads with the DefaultLoader settings. It exits if the config
// cannot be parsed.
func MustLoad(conf interface{}) {
d := New()
d.MustLoad(conf)
}
// MustLoad is like Load but panics if the config cannot be parsed.
func (d *DefaultLoader) MustLoad(conf interface{}) {
if err := d.Load(conf); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
// we at koding, believe having sane defaults in our system, this is the
// reason why we have default validators in DefaultLoader. But do not cause
// nil pointer panics if one uses DefaultLoader directly.
if d.Validator != nil {
d.MustValidate(conf)
}
}
// MustValidate validates the struct. It exits with status 1 if it can't
// validate.
func (d *DefaultLoader) MustValidate(conf interface{}) {
if err := d.Validate(conf); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
}
// fieldSet sets field value from the given string value. It converts the
// string value in a sane way and is usefulf or environment variables or flags
// which are by nature in string types.
func fieldSet(field *structs.Field, v string) error {
switch f := field.Value().(type) {
case flag.Value:
if v := reflect.ValueOf(field.Value()); v.IsNil() {
typ := v.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if err := field.Set(reflect.New(typ).Interface()); err != nil {
return err
}
f = field.Value().(flag.Value)
}
return f.Set(v)
}
// TODO: add support for other types
switch field.Kind() {
case reflect.Bool:
val, err := strconv.ParseBool(v)
if err != nil {
return err
}
if err := field.Set(val); err != nil {
return err
}
case reflect.Int:
i, err := strconv.Atoi(v)
if err != nil {
return err
}
if err := field.Set(i); err != nil {
return err
}
case reflect.String:
if err := field.Set(v); err != nil {
return err
}
case reflect.Slice:
switch t := field.Value().(type) {
case []string:
if err := field.Set(strings.Split(v, ",")); err != nil {
return err
}
case []int:
var list []int
for _, in := range strings.Split(v, ",") {
i, err := strconv.Atoi(in)
if err != nil {
return err
}
list = append(list, i)
}
if err := field.Set(list); err != nil {
return err
}
default:
return fmt.Errorf("multiconfig: field '%s' of type slice is unsupported: %s (%T)",
field.Name(), field.Kind(), t)
}
case reflect.Float64:
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return err
}
if err := field.Set(f); err != nil {
return err
}
case reflect.Int64:
switch t := field.Value().(type) {
case time.Duration:
d, err := time.ParseDuration(v)
if err != nil {
return err
}
if err := field.Set(d); err != nil {
return err
}
case int64:
p, err := strconv.ParseInt(v, 10, 0)
if err != nil {
return err
}
if err := field.Set(p); err != nil {
return err
}
default:
return fmt.Errorf("multiconfig: field '%s' of type int64 is unsupported: %s (%T)",
field.Name(), field.Kind(), t)
}
default:
return fmt.Errorf("multiconfig: field '%s' has unsupported type: %s", field.Name(), field.Kind())
}
return nil
}