File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed
Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments