Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions os/env.go
Original file line number Diff line number Diff line change
@@ -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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this cast won’t work for many types like string to an integer for example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you're right. Need to change to constraint and how to cast the value. But at least the signature will be like that.

}
return defaultValue
}
22 changes: 22 additions & 0 deletions os/env_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}
Loading