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