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
|
package envelope
import (
"os"
"reflect"
)
// LoadFromEnv populates a struct with values from environment variables.
//
// The function takes a pointer to a struct and looks for fields with the `env` tag.
// For each field with an `env` tag, it attempts to load the corresponding environment
// variable and parse it into the field's type.
//
// Supported types include:
// - string
// - bool
// - int, int8, int16, int32, int64
// - uint, uint8, uint16, uint32, uint64
// - float32, float64
// - time.Time (RFC3339 format)
// - time.Duration
// - net.IP
// - net.IPNet (CIDR notation)
// - url.URL
// - []string, []int (comma-separated)
// - Nested structs
// - Custom types (via registered type parsers)
//
// For nested structs, the parent field's `env` tag is used as a prefix for all fields
// in the nested struct. If the parent field doesn't have an `env` tag, no prefix is added.
//
// You can override the default parsers or add support for custom types using
// RegisterTypeParser. This allows you to customize how environment variable values
// are converted to specific types, including the built-in types.
//
// Example:
//
// type Config struct {
// Host string `env:"HOST"`
// Port int `env:"PORT"`
// Timeout time.Duration `env:"TIMEOUT"`
// Server struct {
// MaxConns int `env:"MAX_CONNS"`
// } `env:"SERVER"`
// }
//
// // This would look for environment variables:
// // HOST, PORT, TIMEOUT, SERVER_MAX_CONNS
//
// Returns an error if the input is not a pointer to a struct, or if any value
// cannot be parsed into the corresponding field type.
func LoadFromEnv(ptr any) error {
v := reflect.ValueOf(ptr)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return newNotPointerToStructError(v.Type())
}
v = v.Elem()
return loadStructFromEnv(v, "")
}
func loadStructFromEnv(v reflect.Value, prefix string) error {
t := v.Type()
for i := range t.NumField() {
field := t.Field(i)
fieldValue := v.Field(i)
if !fieldValue.CanSet() {
continue
}
if fieldValue.Kind() == reflect.Struct {
if _, hasParser := typeParserRegistry[fieldValue.Type()]; !hasParser {
if err := loadNestedStructFromEnv(fieldValue, field, prefix); err != nil {
return err
}
continue
}
}
envTag := field.Tag.Get("env")
if envTag == "" {
continue
}
if err := loadFieldFromEnv(fieldValue, field, envTag, prefix); err != nil {
return err
}
}
return nil
}
func loadNestedStructFromEnv(fieldValue reflect.Value, field reflect.StructField, parentPrefix string) error {
// For nested structs, they can have 'env' struct tags
// that indicate a prefix for their nested fields when
// parsing them.
//
// e.g. if the parent struct has a tag of "USER" and it
// has an inner field with a tag of "NAME", the environment
// variable would be "USER_NAME".
var nestedPrefix string
envTag := field.Tag.Get("env")
if envTag != "" {
if parentPrefix != "" {
nestedPrefix = parentPrefix + "_" + envTag
} else {
nestedPrefix = envTag
}
} else {
nestedPrefix = parentPrefix
}
return loadStructFromEnv(fieldValue, nestedPrefix)
}
func loadFieldFromEnv(fieldValue reflect.Value, field reflect.StructField, envTag string, prefix string) error {
envName := buildEnvVarName(envTag, prefix)
envValue := os.Getenv(envName)
if envValue == "" {
return nil
}
return parseAndSetFieldValue(fieldValue, field, envValue, envName)
}
func buildEnvVarName(envTag string, prefix string) string {
if prefix != "" {
return prefix + "_" + envTag
}
return envTag
}
func parseAndSetFieldValue(fieldValue reflect.Value, field reflect.StructField, envValue string, envName string) error {
if parser, exists := typeParserRegistry[fieldValue.Type()]; exists {
val, err := parser.Parse(envValue)
if err != nil {
return newParseError(field.Name, envName, envValue, fieldValue.Type(), err)
}
fieldValue.Set(reflect.ValueOf(val))
return nil
}
return newUnsupportedTypeError(field.Name, fieldValue.Type())
}
|