/
config.go
221 lines (177 loc) · 5.03 KB
/
config.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
package config
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Config is a structure that can populate the exported fields of a
// struct based on the value of the field `env` tags.
type Config interface {
// Init prepares state required by the registered sourcer. This
// method should be called before calling any other method.
Init() error
// Load populates a configuration object. The given tag modifiers
// are applied to the configuration object pre-load. If the target
// value conforms to the PostLoadConfig interface, the PostLoad
// function may be called multiple times.
Load(interface{}, ...TagModifier) error
// MustInject calls Injects and panics on error.
MustLoad(interface{}, ...TagModifier)
// Assets returns a list of names of assets that compose the
// underlying sourcer. This can be a list of matched files that are
// read, or a token that denotes a fixed source.
Assets() []string
// Dump returns the full content of the underlying sourcer. This
// is used by the logging package to show the content of the
// environment and config files when a value is missing or otherwise
// illegal.
Dump() map[string]string
}
// PostLoadConfig is a marker interface for configuration objects
// which should do some post-processing after being loaded. This
// can perform additional casting (e.g. ints to time.Duration) and
// more sophisticated validation (e.g. enum or exclusive values).
type PostLoadConfig interface {
PostLoad() error
}
type config struct {
sourcer Sourcer
}
var _ Config = &config{}
// NewConfig creates a config loader with the given sourcer.
func NewConfig(sourcer Sourcer) Config {
return &config{
sourcer: sourcer,
}
}
func (c *config) Init() error {
return c.sourcer.Init()
}
func (c *config) Load(target interface{}, modifiers ...TagModifier) error {
config, err := ApplyTagModifiers(target, modifiers...)
if err != nil {
return err
}
errors := c.load(config)
if len(errors) == 0 {
sourceFields, _ := getExportedFields(config)
targetFields, _ := getExportedFields(target)
for i := 0; i < len(sourceFields); i++ {
targetFields[i].Field.Set(sourceFields[i].Field)
}
if plc, ok := target.(PostLoadConfig); ok {
if err := plc.PostLoad(); err != nil {
errors = append(errors, err)
}
}
}
return loadError(errors)
}
// MustLoad calls Load and panics on error.
func (c *config) MustLoad(target interface{}, modifiers ...TagModifier) {
if err := c.Load(target, modifiers...); err != nil {
panic(err.Error())
}
}
func (c *config) Assets() []string {
return c.sourcer.Assets()
}
func (c *config) Dump() map[string]string {
return c.sourcer.Dump()
}
func (c *config) load(target interface{}) []error {
objValue, objType, err := getIndirect(target)
if err != nil {
return []error{err}
}
return c.loadStruct(objValue, objType)
}
func (c *config) loadStruct(objValue reflect.Value, objType reflect.Type) []error {
if objType.Kind() != reflect.Struct {
return []error{fmt.Errorf(
"invalid embedded type in configuration struct",
)}
}
errors := []error{}
for i := 0; i < objType.NumField(); i++ {
field := objValue.Field(i)
fieldType := objType.Field(i)
defaultTagValue := fieldType.Tag.Get(DefaultTag)
requiredTagValue := fieldType.Tag.Get(RequiredTag)
if fieldType.Anonymous {
errors = append(errors, c.loadStruct(field, fieldType.Type)...)
continue
}
tagValues := []string{}
for _, tag := range c.sourcer.Tags() {
tagValues = append(tagValues, fieldType.Tag.Get(tag))
}
err := c.loadEnvField(
field,
fieldType.Name,
tagValues,
defaultTagValue,
requiredTagValue,
)
if err != nil {
errors = append(errors, err)
}
}
return errors
}
func (c *config) loadEnvField(
fieldValue reflect.Value,
name string,
tagValues []string,
defaultTag string,
requiredTag string,
) error {
val, flag, err := c.sourcer.Get(tagValues)
if err != nil {
return err
}
if flag == FlagSkip && RequiredTag == "" && DefaultTag == "" {
return nil
}
if !fieldValue.IsValid() {
return fmt.Errorf("field '%s' is invalid", name)
}
if !fieldValue.CanSet() {
return fmt.Errorf("field '%s' can not be set", name)
}
if flag == FlagFound {
if !toJSON([]byte(val), fieldValue.Addr().Interface()) {
return fmt.Errorf("value supplied for field '%s' cannot be coerced into the expected type", name)
}
return nil
}
if requiredTag != "" {
val, err := strconv.ParseBool(requiredTag)
if err != nil {
return fmt.Errorf("field '%s' has an invalid required tag", name)
}
if val {
return fmt.Errorf("no value supplied for field '%s'", name)
}
}
if defaultTag != "" {
if !toJSON([]byte(defaultTag), fieldValue.Addr().Interface()) {
return fmt.Errorf("default value for field '%s' cannot be coerced into the expected type", name)
}
return nil
}
return nil
}
//
// Helpers
func loadError(errors []error) error {
if len(errors) == 0 {
return nil
}
messages := []string{}
for _, err := range errors {
messages = append(messages, err.Error())
}
return fmt.Errorf("failed to load config (%s)", strings.Join(messages, ", "))
}