From ff4ca68dfd54771aab5a1b07918aaea7237fbaaa Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sun, 11 Aug 2024 21:46:08 +0300 Subject: add IntFromENV --- internal/config/config.go | 23 +++++++++++++++++++++++ internal/config/config_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) (limited to 'internal/config') 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() -- cgit v1.2.3