This repository has been archived by the owner on Aug 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.go
181 lines (163 loc) · 4.48 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
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
package env
import (
"encoding"
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
const (
decadicBase = 10
byteSize = 8
envTag = "env"
envTagDive = "dive"
envTagIgnorePrefix = "ignoreprefix"
// envVarAppPrefix is the environment variable that holds the prefix for the
// environment variables specified by the `env` tag.
envVarAppPrefix = "APP_PREFIX"
)
// Apply applies the environment variables to the given target.
func Apply(target any) error {
return ApplyWithPrefix(target, os.Getenv(envVarAppPrefix))
}
// MustApply calls Apply and panics on error.
func MustApply(target any) {
if err := Apply(target); err != nil {
panic(err)
}
}
// ApplyWithPrefix applies the environment variables to the given target.
//
// The prefix is used to prefix the environment variables specified by the `env` tag.
func ApplyWithPrefix(target any, prefix string) error {
rv := reflect.ValueOf(target)
switch rv.Kind() { // nolint:exhaustive
case reflect.Pointer:
typ := rv.Elem().Kind()
if typ != reflect.Struct || rv.IsNil() {
return &InvalidTypeError{rv}
}
default:
return &InvalidTypeError{rv}
}
return applyWithPrefix(rv.Elem(), prefix)
}
// MustApplyWithPrefix calls ApplyWithPrefix and panics on error.
func MustApplyWithPrefix(target any, prefix string) {
if err := ApplyWithPrefix(target, prefix); err != nil {
panic(err)
}
}
func applyWithPrefix(rv reflect.Value, prefix string) error {
rt := rv.Type()
L:
for i := 0; i < rv.NumField(); i++ {
rf := rv.Field(i)
if !rt.Field(i).IsExported() {
continue L
}
tagVal := rt.Field(i).Tag.Get(envTag)
switch tagVal {
case "":
continue L
case "," + envTagDive:
switch k := rf.Kind(); k { // nolint:exhaustive
case reflect.Struct:
if err := applyWithPrefix(rf, prefix); err != nil {
return err
}
case reflect.Pointer:
if rf.IsNil() {
rf.Set(reflect.New(rf.Type().Elem()))
}
if err := applyWithPrefix(rf.Elem(), prefix); err != nil {
return err
}
default:
return fmt.Errorf("%q is not available to kind %q", envTagDive, k)
}
default:
envKey := envKey(tagVal, prefix)
envVal, envValSet := os.LookupEnv(envKey)
if !envValSet {
continue L
}
if err := setValue(envVal, rf); err != nil {
return fmt.Errorf("set env key %q, env value %q: %w", envKey, envVal, err)
}
}
}
return nil
}
func envKey(envVar, prefix string) string {
const ignorePrefix = "," + envTagIgnorePrefix
if strings.Contains(envVar, ignorePrefix) {
//nolint:gocritic
return envVar[:strings.Index(envVar, ",")]
}
if prefix != "" {
return fmt.Sprintf("%s_%s", prefix, envVar)
}
return envVar
}
func setValue(val string, rv reflect.Value) error {
fieldKind := rv.Kind()
fieldType := rv.Type()
if rv.CanAddr() && fieldKind != reflect.Pointer {
rf := rv.Addr()
if um, ok := rf.Interface().(encoding.TextUnmarshaler); ok {
if err := um.UnmarshalText([]byte(val)); err != nil {
return fmt.Errorf("unmarshal value %q: %w", val, err)
}
return nil
}
}
switch fieldKind { //nolint:exhaustive
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(val, decadicBase, int(fieldType.Size()*byteSize))
if err != nil {
return err
}
rv.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(val, decadicBase, int(fieldType.Size()*byteSize))
if err != nil {
return err
}
rv.SetUint(u)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(val, int(fieldType.Size()*byteSize))
if err != nil {
return err
}
rv.SetFloat(f)
case reflect.Bool:
b, err := strconv.ParseBool(val)
if err != nil {
return err
}
rv.SetBool(b)
case reflect.String:
rv.SetString(val)
case reflect.Pointer:
typ := fieldType.Elem()
ptr := reflect.New(typ)
if err := setValue(val, ptr.Elem()); err != nil {
return fmt.Errorf("set value %q: %w", val, err)
}
rv.Set(ptr)
default:
// This case is not recommended, but it is allowed.
// This case is hit when a field type defines encoding.TextUnmashaler on value receiver.
// It is considered resonsibility of the caller to make sure this is the intended use-case.
um, ok := rv.Interface().(encoding.TextUnmarshaler)
if !ok {
return fmt.Errorf("field type %q does not implement encoding.TextUnmarshaler interface", fieldType)
}
if err := um.UnmarshalText([]byte(val)); err != nil {
return fmt.Errorf("unmarshal value %q: %w", val, err)
}
}
return nil
}