diff --git a/common/common.go b/common/common.go new file mode 100644 index 0000000..22a633c --- /dev/null +++ b/common/common.go @@ -0,0 +1,13 @@ +package common + +import "os" + +// GetenvDefault retrieves an environment variable if set, or a provided default +func GetenvDefault(key string, d string) string { + val, ok := os.LookupEnv(key) + if ok { + return val + } else { + return d + } +} diff --git a/common/common_test.go b/common/common_test.go new file mode 100644 index 0000000..9376b1e --- /dev/null +++ b/common/common_test.go @@ -0,0 +1,39 @@ +package common + +import ( + "os" + "testing" +) + +var testEnvKey string = "TEST_MQTT_KEY" + +func assertError(t testing.TB, got, want string) { + t.Helper() + if got != want { + t.Errorf("Error: got '%s', want '%s'", got, want) + } +} + +func TestGetenvDefault(t *testing.T) { + t.Run("key not set", func(t *testing.T) { + originalEnv := os.Getenv(testEnvKey) + os.Unsetenv(testEnvKey) + defer os.Setenv(testEnvKey, originalEnv) + + got := GetenvDefault(testEnvKey, "found") + want := "found" + + assertError(t, got, want) + }) + + t.Run("key set", func(t *testing.T) { + originalEnv := os.Getenv(testEnvKey) + os.Setenv(testEnvKey, "batman") + defer os.Setenv(testEnvKey, originalEnv) + + got := GetenvDefault(testEnvKey, "found") + want := "batman" + assertError(t, got, want) + + }) +}