-
Notifications
You must be signed in to change notification settings - Fork 7
/
env.go
109 lines (88 loc) · 2.17 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
package env
// package main
import (
"errors"
"reflect"
)
// Env struct
type Env struct {
Value reflect.Value // Value is the value of an interface or pointer
Prefix string
Vars []*Var
}
// Process takes a struct, and maps environment variables to its fields.
// Errors returned from underlying functions will bubble up to the surface.
func Process(v interface{}) error {
_, err := NewEnv(v)
if err != nil {
return err
}
return nil
}
// MustProcess maps environment variables to the fields of struct v.
// If any errors are returned, this function will panic.
func MustProcess(v interface{}) {
_, err := NewEnv(v)
if err != nil {
panic(err)
}
}
// FieldNames returns the name of all struct fields as aa slice of strings
func (e *Env) FieldNames() []string {
fieldType := e.Type()
var fieldNames []string
for i := 0; i < fieldType.NumField(); i++ {
field := fieldType.Field(i)
fieldNames = append(fieldNames, field.Name)
}
return fieldNames
}
// Type returns the type of e.Value
func (e *Env) Type() reflect.Type {
return e.Value.Type()
}
var errInvalidValue = errors.New("expected value must be a pointer to a struct")
// New is a shortcut wrapper around NewEnv
func New(v interface{}) (*Env, error) {
return NewEnv(v)
}
// NewEnv returns a new Env
func NewEnv(v interface{}) (*Env, error) {
e := &Env{}
if reflect.TypeOf(v).Kind() != reflect.Ptr {
return nil, errInvalidValue
}
if reflect.ValueOf(v).Elem().Kind() != reflect.Struct {
return nil, errInvalidValue
}
e.SetValue(v)
if err := e.Parse(); err != nil {
return e, err
}
return e, nil
}
// SetValue sets Value of Env e
func (e *Env) SetValue(v interface{}) {
if reflect.TypeOf(v).Kind() == reflect.Ptr {
e.Value = reflect.ValueOf(v).Elem()
} else {
e.Value = reflect.ValueOf(v)
}
}
// SetPrefix sets prefix of Env e
func (e *Env) SetPrefix(prefix string) {
e.Prefix = prefix
}
// Parse parses the config struct into valid Vars
func (e *Env) Parse() error {
for _, name := range e.FieldNames() {
field, _ := e.Value.Type().FieldByName(name)
v, err := NewVar(field)
if err != nil {
return err
}
e.Value.FieldByName(name).Set(v.Value)
e.Vars = append(e.Vars, v)
}
return nil
}