-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
86 lines (73 loc) · 2.09 KB
/
options.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
package env
import (
"errors"
"os"
"time"
)
type (
envParseOpts struct {
envLoader EnvLoader
separator string
defaultOnError bool
timeLayout string
sensitive bool
}
// EnvLoader is an alias for a function that loads values from the env. It mirrors the signature of os.Getenv.
EnvLoader func(key string) string
// EnvParseOption is a means to customize parse options via variadic parameters.
EnvParseOption func(o *envParseOpts) error
)
var (
defaultParseOptions = envParseOpts{
envLoader: os.Getenv,
separator: ",",
defaultOnError: false,
timeLayout: time.RFC3339,
}
)
// WithEnvLoader allows overriding how env vars are loaded.
//
// Primarily used for testing, but feel free to get creative.
func WithEnvLoader(loader EnvLoader) EnvParseOption {
return func(o *envParseOpts) error {
if loader == nil {
return errors.New("env loader function cannot be nil")
}
o.envLoader = loader
return nil
}
}
// WithEnvParseSeparator allows overriding the separated used to parse arrays/slices of a given type.
func WithEnvParseSeparator(sep string) EnvParseOption {
return func(o *envParseOpts) error {
if sep == "" {
return errors.New("separator cannot be empty string")
}
o.separator = sep
return nil
}
}
// WithFallbackToDefaultOnError informs the parser that if an error is encountered during parsing, it should fallback to the default value.
func WithFallbackToDefaultOnError(fallback bool) EnvParseOption {
return func(o *envParseOpts) error {
o.defaultOnError = fallback
return nil
}
}
// WithTimeLayout allows overriding the time layout used to parse time.Time values. Default is RFC3339.
func WithTimeLayout(layout string) EnvParseOption {
return func(o *envParseOpts) error {
if layout == "" {
return errors.New("time layout cannot be empty string")
}
o.timeLayout = layout
return nil
}
}
// WithSensitive informs the parser that the value being parsed is sensitive and should not be logged.
func WithSensitive(sensitive bool) EnvParseOption {
return func(o *envParseOpts) error {
o.sensitive = sensitive
return nil
}
}