-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
199 lines (189 loc) · 5.58 KB
/
parser.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
package env
import (
"context"
"fmt"
"log/slog"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type (
// Parseable represents the types the parser is capable of handling.
Parseable interface {
string | bool | int | uint | int64 | uint64 | float64 | time.Duration | time.Time | url.URL | []string | []bool | []int | []uint | []int64 | []uint64 | []float64 | []time.Duration | []time.Time | []url.URL
}
)
// MustFromEnvOrDefault attempts to parse the environment variable provided. If it is empty or missing, the default value is used.
//
// If an error is encountered, depending on whether the `WithFallbackToDefaultOnError` option is provided it will either fallback or fatally log & exit.
func MustFromEnvOrDefault[T Parseable](ctx context.Context, envVar string, defaultVal T, opts ...EnvParseOption) (dest T) {
parsed, err := FromEnvOrDefault(ctx, envVar, defaultVal, opts...)
if err != nil {
slog.Default().ErrorContext(ctx, "failed to parse env var", slog.String("env_var", envVar), slog.String("error", err.Error()))
os.Exit(1)
}
return parsed
}
// FromEnvOrDefault attempts to parse the environment variable provided. If it is empty or missing, the default value is used.
//
// If an error is encountered, depending on whether the `WithFallbackToDefaultOnError` option is provided it will either fallback or return the error back to the client.
func FromEnvOrDefault[T Parseable](ctx context.Context, envVar string, defaultVal T, opts ...EnvParseOption) (dest T, err error) {
parseOpts := &defaultParseOptions
for _, opt := range opts {
if err := opt(parseOpts); err != nil {
return dest, fmt.Errorf("option error: %w", err)
}
}
envStr := parseOpts.envLoader(envVar)
if envStr == "" {
return defaultVal, nil
}
var (
v any
)
switch any(dest).(type) {
case string:
v = envStr
case bool:
v, err = strconv.ParseBool(envStr)
case int:
v, err = strconv.Atoi(envStr)
case uint:
var i uint64
i, err = strconv.ParseUint(envStr, 10, 64)
v = uint(i)
case int64:
v, err = strconv.ParseInt(envStr, 10, 64)
case uint64:
v, err = strconv.ParseUint(envStr, 10, 64)
case float64:
v, err = strconv.ParseFloat(envStr, 64)
case time.Duration:
v, err = time.ParseDuration(envStr)
case time.Time:
v, err = time.Parse(parseOpts.timeLayout, envStr)
case url.URL:
v, err = url.Parse(envStr)
case []string:
v = strings.Split(envStr, parseOpts.separator)
case []bool:
vs := make([]bool, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.ParseBool(at)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []int:
vs := make([]int, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.Atoi(at)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []uint:
vs := make([]uint, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.ParseUint(at, 10, 64)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, uint(parsed))
}
v = vs
case []int64:
vs := make([]int64, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.ParseInt(at, 10, 64)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []uint64:
vs := make([]uint64, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.ParseUint(at, 10, 64)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []float64:
vs := make([]float64, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := strconv.ParseFloat(at, 64)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []time.Duration:
vs := make([]time.Duration, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := time.ParseDuration(at)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []time.Time:
vs := make([]time.Time, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := time.Parse(parseOpts.timeLayout, at)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, parsed)
}
v = vs
case []url.URL:
vs := make([]url.URL, 0)
for i, at := range splitAndTrim(envStr, parseOpts.separator) {
parsed, innerErr := url.Parse(at)
if innerErr != nil {
err = fmt.Errorf("item %s (pos: %d) failed to parse: %w", at, i, innerErr)
break
}
vs = append(vs, *parsed)
}
v = vs
}
if err != nil {
if parseOpts.defaultOnError {
return defaultVal, nil
}
return dest, fmt.Errorf("failed to parse env %s to %T: %v", envVar, dest, err)
}
dest, ok := v.(T)
if !ok {
return dest, fmt.Errorf("failed to cast env %s to %T", envVar, dest)
}
return dest, nil
}
func splitAndTrim(in string, sep string) []string {
strs := strings.Split(in, sep)
for i, str := range strs {
strs[i] = strings.TrimSpace(str)
}
return strs
}