Skip to content

Commit 4846bab

Browse files
committed
add bool support
1 parent 00e68f7 commit 4846bab

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

env.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ func GetWithFallback(key string, fallback string) string {
3131
return fallback
3232
}
3333

34+
// GetBool returns the value of an environment variable as a boolean.
35+
func GetBool(key string) bool {
36+
return Get(key) == "true"
37+
}
38+
39+
// GetBoolWithFallback returns the value of an environment variable as a boolean
40+
// or a fallback value if the environment variable is not set.
41+
func GetBoolWithFallback(key string, fallback bool) bool {
42+
if value, ok := Lookup(key); ok {
43+
return value == "true"
44+
}
45+
return fallback
46+
}
47+
3448
// Load will read your env file(s) and load them into ENV for this process.
3549
//
3650
// Call this function as close as possible to the start of your program

env_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,50 @@ func TestGetWithFallback(t *testing.T) {
5656
})
5757
}
5858
}
59+
func TestGetBoolWithFallback(t *testing.T) {
60+
tests := []struct {
61+
setValue bool
62+
key string
63+
fallback bool
64+
envValue string
65+
wantValue bool
66+
}{
67+
{
68+
setValue: true,
69+
key: "EXISTING_KEY",
70+
fallback: true,
71+
envValue: "true",
72+
wantValue: true,
73+
},
74+
{
75+
setValue: false,
76+
key: "NON_EXISTING_KEY",
77+
fallback: true,
78+
envValue: "",
79+
wantValue: true,
80+
},
81+
{
82+
setValue: true,
83+
key: "EMPTY_VALUE_KEY",
84+
fallback: false,
85+
envValue: "",
86+
wantValue: false,
87+
},
88+
}
89+
for _, tt := range tests {
90+
t.Run(tt.key, func(t *testing.T) {
91+
// Set the environment variable
92+
if tt.setValue {
93+
os.Setenv(tt.key, tt.envValue)
94+
}
95+
// Call the function under test
96+
got := GetBoolWithFallback(tt.key, tt.fallback)
97+
// Check if the returned value matches the expected value
98+
if got != tt.wantValue {
99+
t.Errorf("GetBoolWithFallback(%q, %v) = %v, want %v", tt.key, tt.fallback, got, tt.wantValue)
100+
}
101+
// Unset the environment variable
102+
os.Unsetenv(tt.key)
103+
})
104+
}
105+
}

0 commit comments

Comments
 (0)