Skip to content

Commit 6775d0b

Browse files
committed
Add Env with default value
1 parent 5c5cc21 commit 6775d0b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

os/env.go

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

os/env_test.go

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

0 commit comments

Comments
 (0)