-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
228 lines (189 loc) · 5.07 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
package minienv
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
type Option func(*LoadConfig) error
type LoadConfig struct {
Prefix string
Values map[string]string
}
// This struct hold all the metadata about a found "env"-tag for a field
type tag struct {
// This is the name of the env variable we need to look for
name string
// This is a flag that tells us if the variable is required
required bool
// This is the default value for the variable, can be empty and therefore invalid
defaultValue string
}
// Load variables from the environment into the provided struct.
// It will try to match environment variables to field that contain an `env` tag.
//
// The obj must be a pointer to a struct.
// Additional options can be supplied for overriding environment variables.
func Load(obj interface{}, options ...Option) error {
// read in any overrides the user wants to do
config := LoadConfig{
Values: make(map[string]string),
}
for _, option := range options {
err := option(&config)
if err != nil {
return err
}
}
// we can only set things if we receive a pointer that points to a struct
p := reflect.ValueOf(obj)
if p.Kind() != reflect.Ptr {
return ErrInvalidInput
}
s := reflect.Indirect(p)
if !s.IsValid() || s.Kind() != reflect.Struct {
return ErrInvalidInput
}
// this will recursively fill the struct
err := handleStruct(s, &config)
if err != nil {
return err
}
return nil
}
// Handles a struct recursively by iterating over its fields
// and then setting the field with the appropiate variable if one was found.
func handleStruct(s reflect.Value, config *LoadConfig) error {
for i := 0; i < s.NumField(); i++ {
// handle recursive cases
field := s.Field(i)
if field.Kind() == reflect.Struct {
handleStruct(field, config)
continue
}
// Check if the tag is present skip if not
tag, found, err := parseTag(s.Type().Field(i))
if !found {
continue
}
// something went wrong parsing the tag
if err != nil {
return LoadError{
Field: s.Type().Field(i).Name,
Err: err,
}
}
// check if we can actually set the field
if !field.IsValid() || !field.CanSet() {
return LoadError{
Field: s.Type().Field(i).Name,
Err: errors.New("field is not valid or cannot be set"),
}
}
// read the value from the environment and from any our overrides
lookup := tag.name
if config.Prefix != "" && !strings.HasPrefix(lookup, config.Prefix) {
lookup = fmt.Sprintf("%s%s", config.Prefix, lookup)
}
envVal, envExists := os.LookupEnv(lookup)
fallbackVal, fallbackExists := config.Values[lookup]
// guard against the cases where we don't have any valeu that we can set
if !envExists && !fallbackExists && tag.required && tag.defaultValue == "" {
return LoadError{
Field: s.Type().Field(i).Name,
Err: errors.New("required field has no value and no default"),
}
}
// Priority:
// 1. Environment
// 2. Fallback
// 3. Default
var val string
if envExists {
val = envVal
} else if fallbackExists {
val = fallbackVal
} else {
val = tag.defaultValue
}
// update the affected field
err = setField(field, val)
if err != nil {
// we wrap the error for some metadata
return LoadError{
Field: s.Type().Field(i).Name,
Err: err,
}
}
}
return nil
}
// Sets a field based on the kind and the provided value
// This here tries to convert the value to the appropiate type
func setField(f reflect.Value, val string) error {
k := f.Kind()
switch k {
// string
case reflect.String:
f.SetString(val)
// int
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.Atoi(val)
if err != nil {
return err
}
f.SetInt(int64(i))
// bool
case reflect.Bool:
b, err := strconv.ParseBool(val)
if err != nil {
return err
}
f.SetBool(b)
// float
case reflect.Float32, reflect.Float64:
fl, err := strconv.ParseFloat(val, 64)
if err != nil {
return err
}
f.SetFloat(fl)
// anything else is not supported
default:
return fmt.Errorf("unsupported type: %v", k.String())
}
return nil
}
// Parses the `env` tag and returns the bundled information about the tag.
// The first return value is the tag itself, the second return value is a flag indicating if the tag was found
// and the third return value is an error if the tag was invalid.
func parseTag(field reflect.StructField) (tag, bool, error) {
required := true
var defaultVal string
value, found := field.Tag.Lookup("env")
if !found {
return tag{}, false, nil
}
// check any tag options
parts := strings.Split(value, ",")
for _, p := range parts[1:] {
trimmed := strings.TrimSpace(p)
splitted := strings.Split(trimmed, "=")
// tag is optional
if splitted[0] == "optional" {
required = false
} else if splitted[0] == "default" {
// if we have more or less than 2 elements we have an invalid tag
if len(splitted) != 2 {
return tag{}, true, errors.New("invalid default tag")
}
defaultVal = splitted[1]
}
}
return tag{
name: parts[0],
required: required,
defaultValue: defaultVal,
}, true, nil
}