// Package envy provides type-safe environment variable access.
//
// It supports automatic conversion from string environment variables to common Go types:
// string, int, int64, float64, bool, and time.Duration.
//
// If an environment variable is not set or cannot be parsed, functions return the zero value
// of the requested type.
package envy
import (
"os"
"strconv"
"time"
)
// Get retrieves an environment variable and converts it to the specified type T.
// Supported types: string, int, int64, float64, bool, time.Duration.
//
// If the environment variable is not set or cannot be parsed, returns the zero value of T.
func Get[T comparable](key string) T {
var zero T
val, ok := os.LookupEnv(key)
if !ok {
return zero
}
var res any
switch any(zero).(type) {
case string:
res = val
case int:
if n, err := strconv.Atoi(val); err == nil {
res = n
}
case int64:
if n, err := strconv.ParseInt(val, 10, 64); err == nil {
res = n
}
case float64:
if f, err := strconv.ParseFloat(val, 64); err == nil {
res = f
}
case bool:
if b, err := strconv.ParseBool(val); err == nil {
res = b
}
case time.Duration:
if d, err := time.ParseDuration(val); err == nil {
res = d
}
}
return res.(T)
}
// GetOrDefault retrieves an environment variable, if not set, returns default value.
// Supported types: string, int, int64, float64, bool, time.Duration.
func GetOrDefault[T comparable](key string, def T) T {
var zero T
if val := Get[T](key); val != zero {
return val
}
return def
}
|