diff --git a/os/env.go b/os/env.go new file mode 100644 index 0000000..538cceb --- /dev/null +++ b/os/env.go @@ -0,0 +1,18 @@ +//go:build go1.18 +// +build go1.18 + +package osext + +import "os" + +// Env retrieves the value of the environment variable named by the key. +// If the variable is present in the environment, its value (which may be empty) is returned. +// Otherwise, the provided defaultValue is returned. +// The function is generic and can return any type T, but the caller must ensure that +// the type assertion is valid for the expected type of the environment variable. +func Env[T any](key string, defaultValue T) T { + if v, ok := os.LookupEnv(key); ok { + return any(v).(T) + } + return defaultValue +} diff --git a/os/env_test.go b/os/env_test.go new file mode 100644 index 0000000..ae359ad --- /dev/null +++ b/os/env_test.go @@ -0,0 +1,22 @@ +//go:build go1.18 +// +build go1.18 + +package osext + +import ( + "os" + "testing" + + . "github.com/go-playground/assert/v2" +) + +func TestEnv(t *testing.T) { + key := "ENV_FOO" + os.Setenv(key, "FOO") + defer os.Clearenv() + + Equal(t, "FOO", Env(key, "default_value")) + + os.Unsetenv(key) + Equal(t, "default_value", Env(key, "default_value")) +}