forked from Mistobaan/env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
var.go
326 lines (276 loc) · 7.54 KB
/
var.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
package env
import (
"fmt"
"os"
"reflect"
_ "regexp"
"strconv"
"strings"
"time"
// YAML not included in golang encode package
"gopkg.in/yaml.v2"
)
// Var struct
type Var struct {
Name string
Key string
Type reflect.Type
Value reflect.Value
Required bool
Decode string
Default reflect.Value
Options []reflect.Value
}
// NewVar returns a new Var
func NewVar(field reflect.StructField) (*Var, error) {
return NewVarWithFunc(field, os.Getenv)
}
// NewVarWithFunc returns a new Var. get returns the value for the given key
func NewVarWithFunc(field reflect.StructField, get func(string) string) (*Var, error) {
newVar := &Var{}
newVar.Parse(field)
value, err := convert(newVar.Type, get(newVar.Key), newVar.Decode)
if err != nil {
return newVar, err
}
newVar.SetValue(value)
if value == reflect.ValueOf(nil) {
if newVar.Required {
return newVar, fmt.Errorf("%s required", newVar.Key)
}
// Check if we have a default value to set, otherwise set the type's zero value
if newVar.Default != reflect.ValueOf(nil) {
newVar.SetValue(newVar.Default)
} else {
newVar.SetValue(reflect.Zero(newVar.Type))
}
}
if len(newVar.Options) > 0 {
if !newVar.optionsContains(newVar.Value) {
return newVar, fmt.Errorf(`%v="%v" not in allowed options: %v`, newVar.Key, newVar.Value, newVar.Options)
}
}
return newVar, nil
}
func (v *Var) optionsContains(s reflect.Value) bool {
for _, v := range v.Options {
if s.Interface() == v.Interface() {
return true
}
}
return false
}
// SetValue sets Var.Value
func (v *Var) SetValue(value reflect.Value) {
v.Value = value
}
// SetName sets Var.Name
func (v *Var) SetName(value string) {
v.Name = value
}
// SetType sets Var.Type
func (v *Var) SetType(value reflect.Type) {
v.Type = value
}
// SetRequired sets Var.Required
func (v *Var) SetRequired(value bool) {
v.Required = value
}
func (v *Var) SetDecode(value string) {
v.Decode = value
}
// SetDefault sets Var.Default
func (v *Var) SetDefault(value reflect.Value) {
v.Default = value
}
// SetOptions sets Var.Options
func (v *Var) SetOptions(values []reflect.Value) {
v.Options = values
}
// SetKey sets Var.Key
func (v *Var) SetKey(value string) {
v.Key = strings.ToUpper(value)
}
// Parse parses the struct tags of each field
func (v *Var) Parse(field reflect.StructField) error {
v.SetName(field.Name)
v.SetType(field.Type)
v.SetKey(v.Name)
tag := field.Tag.Get("env")
if tag == "" {
return nil
}
tagParams := strings.Split(tag, " ")
// Use a map so we can process in specific order with lookups
// Needed to get the decode param processed first
tagParamsMap := make(map[string]string)
for _, tagParam := range tagParams {
var key, value string
option := strings.Split(tagParam, "=")
key = option[0]
if len(option) > 1 {
value = option[1]
}
tagParamsMap[key] = value
}
// Process the decode tag
// Need to be first so we can decode default / options
if value, ok := tagParamsMap["decode"]; ok {
v.SetDecode(value)
// remove the tag as it has been processed
delete(tagParamsMap, "decode")
}
// process remaining tags
for key, value := range tagParamsMap {
switch key {
case "key":
// override the default key if one is specified
v.SetKey(value)
case "required":
// val, _ := strconv.ParseBool(value)
// if val != false {
v.SetRequired(true)
// }
// for completeness, but should have been removed already
case "decode":
// set decode strategy
v.SetDecode(value)
case "default":
d, err := convert(v.Type, value, v.Decode)
if err != nil {
return err
}
v.SetDefault(d)
case "options":
in := strings.Split(value, ",")
// var values []reflect.Value
values := make([]reflect.Value, len(in))
for k, val := range in {
v1, err := convert(v.Type, val, v.Decode)
if err != nil {
return err
}
values[k] = v1
}
v.SetOptions(values)
}
}
return nil
}
// Convert a string into the specified type.
// Return the type's zero value if we receive an empty string
// Use the decode strategy defined
func convert(t reflect.Type, value string, decode string) (reflect.Value, error) {
if value == "" {
return reflect.ValueOf(nil), nil
}
switch decode {
// if no decode defined, try with type and then kind
// if any type is defined then it will be used else fallback to kind
case "":
val, err := convertWithType(t, value)
if (err != nil) {
val, err = convertWithKind(t , value)
}
return val, err
case "kind":
return convertWithKind(t, value)
case "type":
return convertWithType(t, value)
case "yaml":
return convertWithYaml(t, value)
default:
return reflect.ValueOf(nil), conversionError(decode, `unsupported decode`)
}
}
func convertWithKind(t reflect.Type, value string) (reflect.Value, error) {
if value == "" {
return reflect.ValueOf(nil), nil
}
switch t.Kind() {
case reflect.String:
return reflect.ValueOf(value), nil
// ptr.Elem()
// ptr = reflect.ValueOf(value).Elem().Convert(reflect.String)
// return reflect.ValueOf(value), nil
case reflect.Int:
return parseInt(value)
case reflect.Bool:
return parseBool(value)
case reflect.Slice:
return parseSlice(t, value)
case reflect.Map:
return parseMap(t, value)
}
return reflect.ValueOf(nil), conversionError(value, `unsupported `+t.Kind().String())
}
func convertWithType(t reflect.Type, value string) (reflect.Value, error) {
// Use string value of type to determine type
// Avoid declaring temporary vars just to get type
switch t.String() {
case "time.Duration":
result, err := time.ParseDuration(value)
return reflect.ValueOf(result), err
default:
return reflect.ValueOf(nil), conversionError(value, `unsupported type ` + t.String())
}
}
func convertWithYaml(t reflect.Type, value string) (reflect.Value, error) {
return parseYaml(t, value)
}
type errConversion struct {
Value string
Type string
}
func (e *errConversion) Error() string {
return fmt.Sprintf(`could not convert value "%s" into %s type`, e.Value, e.Type)
}
func conversionError(v, t string) *errConversion {
return &errConversion{Value: v, Type: t}
}
func parseInt(value string) (reflect.Value, error) {
if value == "" {
return reflect.Zero(reflect.TypeOf(reflect.Int)), nil
}
i, err := strconv.Atoi(value)
if err != nil {
return reflect.ValueOf(nil), conversionError(value, "int")
}
return reflect.ValueOf(i), nil
}
func parseBool(value string) (reflect.Value, error) {
if value == "" {
return reflect.Zero(reflect.TypeOf(reflect.Int)), nil
}
b, err := strconv.ParseBool(value)
if err != nil {
return reflect.ValueOf(nil), conversionError(value, "bool")
}
return reflect.ValueOf(b), nil
}
func parseFloat(value string) (reflect.Value, error) {
b, err := strconv.ParseFloat(value, 64)
if err != nil {
return reflect.ValueOf(nil), conversionError(value, "float64")
}
return reflect.ValueOf(b), nil
}
// Using YAML syntax by default for slice
// JSON is a subset of YAML syntax, so both will parse
func parseSlice(t reflect.Type, value string) (reflect.Value, error) {
return parseYaml(t, value)
}
// Using YAML syntax by default for map
// JSON is a subset of YAML syntax, so both will parse
func parseMap(t reflect.Type, value string) (reflect.Value, error) {
return parseYaml(t, value)
}
func parseYaml(t reflect.Type, value string) (reflect.Value, error) {
a := reflect.New(t)
err := yaml.Unmarshal([]byte(value), a.Interface())
if err != nil {
fmt.Print(err)
return reflect.ValueOf(nil), conversionError(value, `yaml conversion error; Kind(): ` + t.Kind().String() + `; Type(): ` + t.String())
}
return a.Elem(), nil
}