Skip to content

Commit 6bad82f

Browse files
committed
feat: add utility to get boolean env var
1 parent 1f807fc commit 6bad82f

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

src/util/env.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package util
2+
3+
import (
4+
"os"
5+
"strings"
6+
)
7+
8+
func GetBoolEnv(key string) bool {
9+
return isTruthyEnvValue(os.Getenv(key))
10+
}
11+
12+
func isTruthyEnvValue(value string) bool {
13+
valueLen := len(value)
14+
15+
if valueLen == 0 {
16+
return false
17+
}
18+
19+
if strings.EqualFold(value, "false") {
20+
return false
21+
}
22+
23+
for i := 0; i < valueLen; i++ {
24+
if value[i] != '0' {
25+
return true
26+
}
27+
}
28+
29+
return false
30+
}

src/util/env_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package util
2+
3+
import "testing"
4+
5+
func TestIsTruthyEnvValue(t *testing.T) {
6+
expect := func(input string, expectResult bool) bool {
7+
result := isTruthyEnvValue(input)
8+
return result == expectResult
9+
}
10+
11+
if !expect("", false) {
12+
t.Error()
13+
}
14+
15+
if !expect("false", false) {
16+
t.Error()
17+
}
18+
19+
if !expect("fAlse", false) {
20+
t.Error()
21+
}
22+
23+
if !expect("true", true) {
24+
t.Error()
25+
}
26+
27+
if !expect("truE", true) {
28+
t.Error()
29+
}
30+
31+
if !expect("1", true) {
32+
t.Error()
33+
}
34+
35+
if !expect("0", false) {
36+
t.Error()
37+
}
38+
39+
if !expect("0000", false) {
40+
t.Error()
41+
}
42+
}

0 commit comments

Comments
 (0)