forked from heetch/confita
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
203 lines (165 loc) · 3.81 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
package confita
import (
"context"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/heetch/confita/backend"
"github.com/heetch/confita/backend/env"
)
// Loader loads configuration keys from backends and stores them is a struct.
type Loader struct {
backends []backend.Backend
}
// NewLoader creates a Loader. If no backend is specified, the loader uses the environment.
func NewLoader(backends ...backend.Backend) *Loader {
l := Loader{
backends: backends,
}
if len(l.backends) == 0 {
l.backends = append(l.backends, env.NewBackend())
}
return &l
}
// Load analyses all the fields of the given struct for a "config" tag and queries each backend
// in order for the corresponding key. The given context can be used for timeout and cancelation.
func (l *Loader) Load(ctx context.Context, to interface{}) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
ref := reflect.ValueOf(to)
if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.Elem().Kind() != reflect.Struct {
return errors.New("provided target must be a pointer to struct")
}
ref = ref.Elem()
return l.parseStruct(ctx, &ref)
}
func (l *Loader) parseStruct(ctx context.Context, ref *reflect.Value) error {
t := ref.Type()
numFields := ref.NumField()
for i := 0; i < numFields; i++ {
field := t.Field(i)
value := ref.Field(i)
typ := value.Type()
// skip if field is unexported
if field.PkgPath != "" {
continue
}
tag := field.Tag.Get("config")
if tag == "-" {
continue
}
// if struct or *struct, parse recursively
switch {
case typ.Kind() == reflect.Struct:
err := l.parseStruct(ctx, &value)
if err != nil {
return err
}
continue
case typ.Kind() == reflect.Ptr:
if value.Type().Elem().Kind() == reflect.Struct && !value.IsNil() {
value = value.Elem()
err := l.parseStruct(ctx, &value)
if err != nil {
return err
}
continue
}
}
if tag == "" {
continue
}
key := tag
var required bool
if idx := strings.Index(tag, ","); idx != -1 {
key = tag[:idx]
if tag[idx+1:] == "required" {
required = true
}
}
var found bool
for _, b := range l.backends {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if u, ok := b.(backend.ValueUnmarshaler); ok {
err := u.UnmarshalValue(ctx, key, value.Addr().Interface())
if err != nil && err != backend.ErrNotFound {
return err
}
continue
}
raw, err := b.Get(ctx, key)
if err != nil {
if err == backend.ErrNotFound {
continue
}
return err
}
err = convert(string(raw), &value)
if err != nil {
return err
}
found = true
break
}
if required && !found {
return fmt.Errorf("required key '%s' for field '%s' not found", key, field.Name)
}
}
return nil
}
func convert(data string, value *reflect.Value) error {
k := value.Kind()
t := value.Type()
switch {
case t.String() == "time.Duration":
d, err := time.ParseDuration(data)
if err != nil {
return err
}
value.SetInt(int64(d))
case k == reflect.Bool:
b, err := strconv.ParseBool(data)
if err != nil {
return err
}
value.SetBool(b)
case k >= reflect.Int && k <= reflect.Int64:
i, err := strconv.ParseInt(data, 10, 64)
if err != nil {
return err
}
value.SetInt(i)
case k >= reflect.Uint && k <= reflect.Uint64:
i, err := strconv.ParseUint(data, 10, 64)
if err != nil {
return err
}
value.SetUint(i)
case k >= reflect.Float32 && k <= reflect.Float64:
f, err := strconv.ParseFloat(data, 64)
if err != nil {
return err
}
value.SetFloat(f)
case k == reflect.String:
value.SetString(data)
case k == reflect.Ptr:
n := reflect.New(value.Type().Elem())
value.Set(n)
e := n.Elem()
return convert(data, &e)
default:
return fmt.Errorf("field type '%s' not supported", k)
}
return nil
}