-
Notifications
You must be signed in to change notification settings - Fork 61
/
env.go
387 lines (347 loc) · 9.84 KB
/
env.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
// Copyright 2018 Netflix, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package env provides an `env` struct field tag to marshal and unmarshal
// environment variables.
package env
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
)
const (
// tagKeyDefault is the key used in the struct field tag to specify a default
tagKeyDefault = "default"
// tagKeyRequired is the key used in the struct field tag to specify that the
// field is required
tagKeyRequired = "required"
// tagKeySeparator is the key used in the struct field tag to specify a
// separator for slice fields
tagKeySeparator = "separator"
)
var (
// ErrInvalidValue returned when the value passed to Unmarshal is nil or not a
// pointer to a struct.
ErrInvalidValue = errors.New("value must be a non-nil pointer to a struct")
// ErrUnsupportedType returned when a field with tag "env" is unsupported.
ErrUnsupportedType = errors.New("field is an unsupported type")
// ErrUnexportedField returned when a field with tag "env" is not exported.
ErrUnexportedField = errors.New("field must be exported")
// unmarshalType is the reflect.Type element of the Unmarshaler interface
unmarshalType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
)
// ErrMissingRequiredValue returned when a field with required=true contains no value or default
type ErrMissingRequiredValue struct {
// Value is the type of value that is required to provide error context to
// the caller
Value string
}
func (e ErrMissingRequiredValue) Error() string {
return fmt.Sprintf("value for this field is required [%s]", e.Value)
}
// Unmarshal parses an EnvSet and stores the result in the value pointed to by
// v. Fields that are matched in v will be deleted from EnvSet, resulting in
// an EnvSet with the remaining environment variables. If v is nil or not a
// pointer to a struct, Unmarshal returns an ErrInvalidValue.
//
// Fields tagged with "env" will have the unmarshalled EnvSet of the matching
// key from EnvSet. If the tagged field is not exported, Unmarshal returns
// ErrUnexportedField.
//
// If the field has a type that is unsupported, Unmarshal returns
// ErrUnsupportedType.
func Unmarshal(es EnvSet, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return ErrInvalidValue
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
return ErrInvalidValue
}
t := rv.Type()
for i := range rv.NumField() {
valueField := rv.Field(i)
if valueField.Kind() == reflect.Struct {
if !valueField.Addr().CanInterface() {
continue
}
if err := Unmarshal(es, valueField.Addr().Interface()); err != nil {
return err
}
}
typeField := t.Field(i)
tag := typeField.Tag.Get("env")
if tag == "" {
continue
}
if !valueField.CanSet() {
return ErrUnexportedField
}
envTag := parseTag(tag)
var (
envValue string
ok bool
)
for _, envKey := range envTag.Keys {
envValue, ok = es[envKey]
if ok {
break
}
}
if !ok {
if envTag.Default != "" {
envValue = envTag.Default
} else if envTag.Required {
return &ErrMissingRequiredValue{Value: envTag.Keys[0]}
} else {
continue
}
}
if err := set(typeField.Type, valueField, envValue, envTag.Separator); err != nil {
return err
}
delete(es, tag)
}
return nil
}
func set(t reflect.Type, f reflect.Value, value, sliceSeparator string) error {
// See if the type implements Unmarshaler and use that first,
// otherwise, fallback to the previous logic
var isUnmarshaler bool
isPtr := t.Kind() == reflect.Ptr
if isPtr {
isUnmarshaler = t.Implements(unmarshalType) && f.CanInterface()
} else if f.CanAddr() {
isUnmarshaler = f.Addr().Type().Implements(unmarshalType) && f.Addr().CanInterface()
}
if isUnmarshaler {
var ptr reflect.Value
if isPtr {
// In the pointer case, we need to create a new element to have an
// address to point to
ptr = reflect.New(t.Elem())
} else {
// And for scalars, we need the pointer to be able to modify the value
ptr = f.Addr()
}
if u, ok := ptr.Interface().(Unmarshaler); ok {
if err := u.UnmarshalEnvironmentValue(value); err != nil {
return err
}
if isPtr {
f.Set(ptr)
}
return nil
}
}
switch t.Kind() {
case reflect.Ptr:
ptr := reflect.New(t.Elem())
if err := set(t.Elem(), ptr.Elem(), value, sliceSeparator); err != nil {
return err
}
f.Set(ptr)
case reflect.String:
f.SetString(value)
case reflect.Bool:
v, err := strconv.ParseBool(value)
if err != nil {
return err
}
f.SetBool(v)
case reflect.Float32:
v, err := strconv.ParseFloat(value, 32)
if err != nil {
return err
}
f.SetFloat(v)
case reflect.Float64:
v, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
f.SetFloat(v)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if t.PkgPath() == "time" && t.Name() == "Duration" {
duration, err := time.ParseDuration(value)
if err != nil {
return err
}
f.Set(reflect.ValueOf(duration))
break
}
v, err := strconv.Atoi(value)
if err != nil {
return err
}
f.SetInt(int64(v))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
f.SetUint(v)
case reflect.Slice:
if sliceSeparator == "" {
sliceSeparator = "|"
}
values := strings.Split(value, sliceSeparator)
switch t.Elem().Kind() {
case reflect.String:
// already []string, just set directly
f.Set(reflect.ValueOf(values))
default:
dest := reflect.MakeSlice(reflect.SliceOf(t.Elem()), len(values), len(values))
for i, v := range values {
if err := set(t.Elem(), dest.Index(i), v, sliceSeparator); err != nil {
return err
}
}
f.Set(dest)
}
default:
return ErrUnsupportedType
}
return nil
}
// UnmarshalFromEnviron parses an EnvSet from os.Environ and stores the result
// in the value pointed to by v. Fields that weren't matched in v are returned
// in an EnvSet with the remaining environment variables. If v is nil or not a
// pointer to a struct, UnmarshalFromEnviron returns an ErrInvalidValue.
//
// Fields tagged with "env" will have the unmarshalled EnvSet of the matching
// key from EnvSet. If the tagged field is not exported, UnmarshalFromEnviron
// returns ErrUnexportedField.
//
// If the field has a type that is unsupported, UnmarshalFromEnviron returns
// ErrUnsupportedType.
func UnmarshalFromEnviron(v interface{}) (EnvSet, error) {
es, err := EnvironToEnvSet(os.Environ())
if err != nil {
return nil, err
}
return es, Unmarshal(es, v)
}
// Marshal returns an EnvSet of v. If v is nil or not a pointer, Marshal returns
// an ErrInvalidValue.
//
// Marshal uses fmt.Sprintf to transform encountered values to its default
// string format. Values without the "env" field tag are ignored.
//
// Nested structs are traversed recursively.
func Marshal(v interface{}) (EnvSet, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return nil, ErrInvalidValue
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
return nil, ErrInvalidValue
}
es := make(EnvSet)
t := rv.Type()
for i := range rv.NumField() {
valueField := rv.Field(i)
if valueField.Kind() == reflect.Struct {
if !valueField.Addr().CanInterface() {
continue
}
nes, err := Marshal(valueField.Addr().Interface())
if err != nil {
return nil, err
}
for k, v := range nes {
es[k] = v
}
}
typeField := t.Field(i)
tag := typeField.Tag.Get("env")
if tag == "" {
continue
}
envKeys := strings.Split(tag, ",")
var el interface{}
if typeField.Type.Kind() == reflect.Ptr {
if valueField.IsNil() {
continue
}
el = valueField.Elem().Interface()
} else {
el = valueField.Interface()
}
var (
err error
envValue string
)
if m, ok := el.(Marshaler); ok {
envValue, err = m.MarshalEnvironmentValue()
if err != nil {
return nil, err
}
} else {
envValue = fmt.Sprintf("%v", el)
}
for _, envKey := range envKeys {
// Skip keys with '=', as they represent tag options and not environment variable names.
if strings.Contains(envKey, "=") {
switch strings.ToLower(strings.SplitN(envKey, "=", 2)[0]) {
case "separator", "required", "default":
continue
}
}
es[envKey] = envValue
}
}
return es, nil
}
// tag is a struct used to store the parsed "env" field tag when unmarshalling.
type tag struct {
// Keys is used to store the keys specified in the "env" field tag
Keys []string
// Default is used to specify a default value for the field
Default string
// Required is used to specify that the field is required
Required bool
// Separator is used to split the value of a slice field
Separator string
}
// parseTag is used in the Unmarshal function to parse the "env" field tags
// into a tag struct for use in the set function.
func parseTag(tagString string) tag {
var t tag
envKeys := strings.Split(tagString, ",")
for _, key := range envKeys {
if !strings.Contains(key, "=") {
t.Keys = append(t.Keys, key)
continue
}
keyData := strings.SplitN(key, "=", 2)
switch strings.ToLower(keyData[0]) {
case tagKeyDefault:
t.Default = keyData[1]
case tagKeyRequired:
t.Required = strings.ToLower(keyData[1]) == "true"
case tagKeySeparator:
t.Separator = keyData[1]
default:
// just ignoring unsupported keys
continue
}
}
return t
}