forked from vrischmann/envconfig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envconfig.go
311 lines (249 loc) · 6.19 KB
/
envconfig.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
package envconfig
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
)
// Unmarshaler is the interface implemented by objects that can unmarshal
// a environment variable string of themselves.
type Unmarshaler interface {
Unmarshal(s string) error
}
// Init reads the configuration from environment variables and populates the conf object. conf must be a pointer
func Init(conf interface{}) error {
value := reflect.ValueOf(conf)
if value.Kind() != reflect.Ptr {
return errors.New("envconfig: value is not a pointer")
}
elem := value.Elem()
switch elem.Kind() {
case reflect.Ptr:
elem.Set(reflect.New(elem.Type().Elem()))
return readStruct(elem.Elem(), "")
case reflect.Struct:
return readStruct(elem, "")
default:
return errors.New("envconfig: invalid value kind, only works on structs")
}
}
type tag struct {
customName string
optional bool
}
func parseTag(s string) *tag {
tag := &tag{}
tokens := strings.Split(s, ",")
if len(tokens) == 0 {
return tag
}
for _, v := range tokens {
if v == "optional" {
tag.optional = true
} else {
tag.customName = v
}
}
return tag
}
func readStruct(value reflect.Value, parentName string) (err error) {
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
name := value.Type().Field(i).Name
tag := parseTag(value.Type().Field(i).Tag.Get("envconfig"))
var combinedName string
if tag.customName != "" {
combinedName = tag.customName
} else {
combinedName = combineName(parentName, name)
}
doRead:
switch field.Kind() {
case reflect.Ptr:
// it's a pointer, create a new value and restart the switch
field.Set(reflect.New(field.Type().Elem()))
field = field.Elem()
goto doRead
case reflect.Struct:
err = readStruct(field, combinedName)
default:
err = setField(field, combinedName, tag.customName != "", tag.optional)
}
if err != nil {
return err
}
}
return
}
func setField(value reflect.Value, name string, customName, optional bool) (err error) {
str, err := readValue(name, customName, optional)
if err != nil {
return err
}
switch value.Kind() {
case reflect.Slice:
return setSliceField(value, str)
default:
return parseValue(value, str)
}
return
}
func setSliceField(value reflect.Value, str string) error {
elType := value.Type().Elem()
tnz := newSliceTokenizer(str)
slice := reflect.MakeSlice(value.Type(), value.Len(), value.Cap())
for tnz.scan() {
token := tnz.text()
el := reflect.New(elType).Elem()
if err := parseValue(el, token); err != nil {
return err
}
slice = reflect.Append(slice, el)
}
value.Set(slice)
return tnz.Err()
}
var (
durationType = reflect.TypeOf(new(time.Duration)).Elem()
unmarshalerType = reflect.TypeOf(new(Unmarshaler)).Elem()
)
func isDurationField(t reflect.Type) bool {
return t.AssignableTo(durationType)
}
func isUnmarshaler(t reflect.Type) bool {
return t.Implements(unmarshalerType) || reflect.PtrTo(t).Implements(unmarshalerType)
}
func parseValue(v reflect.Value, str string) (err error) {
vtype := v.Type()
// Special case for Unmarshaler
if isUnmarshaler(vtype) {
return parseWithUnmarshaler(v, str)
}
// Special case for time.Duration
if isDurationField(vtype) {
return parseDuration(v, str)
}
kind := v.Type().Kind()
switch kind {
case reflect.Bool:
err = parseBoolValue(v, str)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = parseIntValue(v, str)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
err = parseUintValue(v, str)
case reflect.Float32, reflect.Float64:
err = parseFloatValue(v, str)
case reflect.Ptr:
v.Set(reflect.New(vtype.Elem()))
return parseValue(v.Elem(), str)
case reflect.String:
v.SetString(str)
case reflect.Struct:
err = parseStruct(v, str)
default:
return fmt.Errorf("envconfig: slice element type %v not supported", kind)
}
return
}
func parseWithUnmarshaler(v reflect.Value, str string) error {
var u Unmarshaler
vtype := v.Type()
if vtype.Implements(unmarshalerType) {
u = v.Interface().(Unmarshaler)
} else if reflect.PtrTo(vtype).Implements(unmarshalerType) {
// We know the interface has a pointer receiver, but our value might not be a pointer, so we get one
if v.Kind() != reflect.Ptr {
u = v.Addr().Interface().(Unmarshaler)
} else {
u = v.Interface().(Unmarshaler)
}
}
return u.Unmarshal(str)
}
func parseDuration(v reflect.Value, str string) error {
d, err := time.ParseDuration(str)
if err != nil {
return nil
}
v.SetInt(int64(d))
return nil
}
func parseStruct(value reflect.Value, token string) error {
tokens := strings.Split(token[1:len(token)-1], ",")
if len(tokens) == 0 {
return errors.New("envconfig: struct token should not be empty")
}
if len(tokens) != value.NumField() {
return fmt.Errorf("envconfig: struct token has %d fields but struct has %d",
len(tokens), value.NumField(),
)
}
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
t := tokens[i]
if err := parseValue(field, t); err != nil {
return err
}
}
return nil
}
func parseBoolValue(v reflect.Value, str string) error {
val, err := strconv.ParseBool(str)
if err != nil {
return err
}
v.SetBool(val)
return nil
}
func parseIntValue(v reflect.Value, str string) error {
val, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return err
}
v.SetInt(val)
return nil
}
func parseUintValue(v reflect.Value, str string) error {
val, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return err
}
v.SetUint(val)
return nil
}
func parseFloatValue(v reflect.Value, str string) error {
val, err := strconv.ParseFloat(str, 64)
if err != nil {
return err
}
v.SetFloat(val)
return nil
}
func nameToKey(name string) string {
s := strings.Replace(name, ".", "_", -1)
s = strings.ToUpper(s)
return s
}
func combineName(parentName, name string) string {
if parentName == "" {
return name
}
return parentName + "." + name
}
func readValue(name string, customName, optional bool) (string, error) {
key := name
if !customName {
key = nameToKey(name)
}
str := os.Getenv(key)
if str != "" {
return str, nil
}
if optional {
return str, nil
}
return "", fmt.Errorf("envconfig: key %v not found", key)
}