Skip to content

Commit 15855de

Browse files
committed
Add Env with default value
1 parent 5c5cc21 commit 15855de

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

os/env.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package osext
2+
3+
import "os"
4+
5+
// Env retrieves the value of the environment variable named by the key.
6+
// If the variable is present in the environment, its value (which may be empty) is returned.
7+
// Otherwise, the provided defaultValue is returned.
8+
// The function is generic and can return any type T, but the caller must ensure that
9+
// the type assertion is valid for the expected type of the environment variable.
10+
func Env[T any](key string, defaultValue T) T {
11+
if v, ok := os.LookupEnv(key); ok {
12+
return any(v).(T)
13+
}
14+
return defaultValue
15+
}

os/env_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package osext
2+
3+
import (
4+
"os"
5+
"testing"
6+
7+
. "github.com/go-playground/assert/v2"
8+
)
9+
10+
func TestEnv(t *testing.T) {
11+
key := "ENV_FOO"
12+
os.Setenv(key, "FOO")
13+
defer os.Clearenv()
14+
15+
Equal(t, "FOO", Env(key, "default_value"))
16+
17+
os.Unsetenv(key)
18+
Equal(t, "default_value", Env(key, "default_value"))
19+
}

0 commit comments

Comments
 (0)