summaryrefslogtreecommitdiff
path: root/internal/config
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2024-08-11 21:46:08 +0300
committerPaul Buetow <paul@buetow.org>2024-08-11 21:46:08 +0300
commitff4ca68dfd54771aab5a1b07918aaea7237fbaaa (patch)
treee86923327afc472360f00be0c3e801cc966160df /internal/config
parent7305f1262a364d34ff8ffa529e7eb0daa553a1fe (diff)
add IntFromENV
Diffstat (limited to 'internal/config')
-rw-r--r--internal/config/config.go23
-rw-r--r--internal/config/config_test.go36
2 files changed, 59 insertions, 0 deletions
diff --git a/internal/config/config.go b/internal/config/config.go
index d697434..e078bed 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"io"
"os"
+ "strconv"
"unicode"
)
@@ -42,6 +43,28 @@ func FromENV(keys ...string) string {
return ""
}
+func IntFromENV(keys ...any) int {
+ for _, key := range keys {
+ switch key := key.(type) {
+ case string:
+ if key == "" || !isAllUpperCase(key) {
+ continue
+ }
+ strValue := os.Getenv(key)
+ if strValue == "" {
+ continue
+ }
+ if value, err := strconv.Atoi(strValue); err == nil {
+ return value
+ }
+ case int:
+ return key
+ }
+ }
+
+ return 0
+}
+
func isAllUpperCase(s string) bool {
for _, r := range s {
if unicode.IsLetter(r) && !unicode.IsUpper(r) {
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index f22b336..e1329d3 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -41,6 +41,42 @@ func TestFromENV(t *testing.T) {
t.Logf("got '%s' as expected", expected)
}
+func TestIntFromENV(t *testing.T) {
+ t.Parallel()
+
+ os.Setenv("GOS_TEST_INT_FROM_ENV", "1")
+
+ var (
+ expected = 1
+ got = IntFromENV(t, "GOS_TEST_INT_FROM_ENV")
+ )
+
+ if got != expected {
+ t.Errorf("got '%d' but expected '%d'", got, expected)
+ }
+ t.Logf("got '%d' as expected", expected)
+
+ expected = 999
+ got = IntFromENV("GOS_JAJAJA", expected)
+ if got != expected {
+ t.Errorf("got '%d' but expected '%d'", got, expected)
+ }
+ t.Logf("got '%d' as expected", expected)
+
+ os.Unsetenv("JUJUJU_NOT_EXISTANT_ENV")
+ if got = IntFromENV("JUJUJU_NOT_EXISTANT_ENV"); got != 0 {
+ t.Errorf("got '%d' but expected zero", got)
+ }
+ t.Logf("got zero as expected")
+
+ expected = 1234
+ got = IntFromENV("GOS_WATCH", "", "", "", expected, "")
+ if got != expected {
+ t.Errorf("got '%d' but expected '%d'", got, expected)
+ }
+ t.Logf("got '%d' as expected", expected)
+}
+
func TestSecondENV(t *testing.T) {
t.Parallel()