-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
unmarshal.go
311 lines (277 loc) · 7.52 KB
/
unmarshal.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
package env
import (
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
)
// Unmarshal reads environment variables into a struct based on `env` tags.
func Unmarshal(data interface{}) error {
return unmarshalWithPrefix(data, "")
}
// unmarshalWithPrefix unmarshals environment variables into a struct with a given prefix.
func unmarshalWithPrefix(data interface{}, prefix string) error {
v := reflect.ValueOf(data).Elem()
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldType := t.Field(i)
tag := fieldType.Tag.Get("env")
// Handle nested structs with optional prefixes
if field.Kind() == reflect.Struct {
if err := unmarshalStruct(field.Addr().Interface(), prefix, tag); err != nil {
return err
}
continue
}
if tag == "" {
continue
}
if err := unmarshalField(field, tag, prefix, data); err != nil {
return err
}
}
return nil
}
// unmarshalStruct handles unmarshaling nested structs
func unmarshalStruct(data interface{}, prefix, tag string) error {
newPrefix := prefix
if tag != "" {
newPrefix = prefix + tag + "_"
}
return unmarshalWithPrefix(data, newPrefix)
}
// unmarshalField handles unmarshaling individual fields based on tags
func unmarshalField(field reflect.Value, tag string, prefix string, structPtr interface{}) error {
tagOpts := parseTag(tag)
value, found := findFieldValue(tagOpts.keys, prefix)
if tagOpts.file && found {
fileContent, err := readFileContent(value)
if err != nil {
return err
}
value = fileContent
found = true
}
if !found && tagOpts.fallback != "" {
value = tagOpts.fallback
}
if tagOpts.expand {
value = expandVariables(value, structPtr)
}
if tagOpts.required && value == "" {
return fmt.Errorf("required environment variable %s is not set", tagOpts.keys[0])
}
if found || value != "" {
return setField(field, value)
}
return nil
}
// expandVariables replaces placeholders with actual environment variable values or defaults if not set.
func expandVariables(value string, structPtr interface{}) string {
// Handle both ${var} and $var syntax
re := regexp.MustCompile(`\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)`)
matches := re.FindAllStringSubmatch(value, -1)
for _, match := range matches {
var envVar string
if match[1] != "" {
envVar = match[1] // ${var} syntax
} else {
envVar = match[2] // $var syntax
}
envValue, ok := Lookup(envVar) // Lookup the environment variable; use default if not set
if !ok {
envValue = getDefaultFromStruct(envVar, structPtr)
}
value = strings.Replace(value, match[0], envValue, -1)
}
return value
}
// getDefaultFromStruct retrieves the default value from the struct if available
func getDefaultFromStruct(fieldName string, structPtr interface{}) string {
v := reflect.ValueOf(structPtr).Elem()
t := v.Type()
for i := 0; i < v.NumField(); i++ {
fieldType := t.Field(i)
tag := fieldType.Tag.Get("env")
tagOpts := parseTag(tag)
if tagOpts.keys[0] == fieldName {
if tagOpts.fallback != "" {
return tagOpts.fallback
}
}
// Handle nested structs
if fieldType.Type.Kind() == reflect.Struct {
nestedStructPtr := v.Field(i).Addr().Interface()
nestedValue := getDefaultFromStruct(fieldName, nestedStructPtr)
if nestedValue != "" {
return nestedValue
}
}
}
return ""
}
// Helper function to read file content
func readFileContent(filePath string) (string, error) {
content, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
return string(content), nil
}
// findFieldValue tries to find environment variable value based on keys
func findFieldValue(keys []string, prefix string) (string, bool) {
for _, key := range keys {
fullKey := prefix + key
if val, ok := Lookup(fullKey); ok {
return val, true
}
}
return "", false
}
// tagOptions holds parsed tag options
type tagOptions struct {
keys []string
fallback string
required bool
file bool
expand bool
}
// parseTag parses the struct tag into tagOptions
func parseTag(tag string) tagOptions {
parts := strings.SplitN(tag, ",", 2)
keys := strings.Split(parts[0], "|")
var fallbackValue string
required := false
file := false
expand := false
if len(parts) > 1 {
extraParts := parts[1]
inBrackets := false
start := 0
for i := 0; i < len(extraParts); i++ {
switch extraParts[i] {
case '[':
inBrackets = true
case ']':
inBrackets = false
case ',':
if !inBrackets {
part := extraParts[start:i]
start = i + 1
parsePart(part, &fallbackValue, &required, &file, &expand)
}
}
}
part := extraParts[start:]
parsePart(part, &fallbackValue, &required, &file, &expand)
}
return tagOptions{
keys: keys,
fallback: fallbackValue,
required: required,
file: file,
expand: expand,
}
}
func parsePart(part string, fallbackValue *string, required *bool, file *bool, expand *bool) {
if strings.Contains(part, "default=[") || strings.Contains(part, "fallback=[") {
re := regexp.MustCompile(`(?:default|fallback)=\[(.*?)]`)
matches := re.FindStringSubmatch(part)
if len(matches) > 1 {
*fallbackValue = matches[1]
}
} else if strings.Contains(part, "default=") || strings.Contains(part, "fallback=") {
re := regexp.MustCompile(`(?:default|fallback)=([^,]+)`)
matches := re.FindStringSubmatch(part)
if len(matches) > 1 {
*fallbackValue = matches[1]
}
} else if strings.TrimSpace(part) == "required" {
*required = true
} else if strings.TrimSpace(part) == "file" {
*file = true
} else if strings.TrimSpace(part) == "expand" {
*expand = true
}
}
// setField sets the value of a struct field based on its type
func setField(field reflect.Value, value string) error {
if value == "" {
return nil
}
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Bool:
boolValue, err := parseBool(value)
if err != nil {
return err
}
field.SetBool(boolValue)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
field.SetInt(intValue)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uintValue, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return err
}
field.SetUint(uintValue)
case reflect.Float32, reflect.Float64:
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
field.SetFloat(floatValue)
case reflect.Slice:
elemType := field.Type().Elem()
switch elemType.Kind() {
case reflect.String:
field.Set(reflect.ValueOf(strings.Split(value, ",")))
case reflect.Bool:
boolSlice, err := parseBoolSlice(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(boolSlice))
case reflect.Int:
intSlice, err := parseIntSlice(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(intSlice))
case reflect.Uint:
uintSlice, err := parseUintSlice(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(uintSlice))
case reflect.Float64:
floatSlice, err := parseFloatSlice(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(floatSlice))
default:
return fmt.Errorf("unsupported slice element kind %s", elemType.Kind())
}
default:
return fmt.Errorf("unsupported kind %s", field.Kind())
}
return nil
}
// isZeroValue checks if the given field has a zero value
func isZeroValue(field reflect.Value) bool {
if !field.IsValid() {
return true
}
zeroValue := reflect.Zero(field.Type()).Interface()
currentValue := field.Interface()
return reflect.DeepEqual(zeroValue, currentValue)
}