all repos

x @ main

go extra()

x/envy/env.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
docs(is, envy): add docs, 5 months ago
1
// Package envy provides type-safe environment variable access.
2
//
3
// It supports automatic conversion from string environment variables to common Go types:
4
// string, int, int64, float64, bool, and time.Duration.
5
//
6
// If an environment variable is not set or cannot be parsed, functions return the zero value
7
// of the requested type.
8
package envy
9
10
import (
11
	"os"
12
	"strconv"
13
	"time"
14
)
15
16
// Get retrieves an environment variable and converts it to the specified type T.
17
// Supported types: string, int, int64, float64, bool, time.Duration.
18
//
19
// If the environment variable is not set or cannot be parsed, returns the zero value of T.
20
func Get[T comparable](key string) T {
21
	var zero T
22
	val, ok := os.LookupEnv(key)
23
	if !ok {
24
		return zero
25
	}
26
27
	var res any
28
	switch any(zero).(type) {
29
	case string:
30
		res = val
31
	case int:
32
		if n, err := strconv.Atoi(val); err == nil {
33
			res = n
34
		}
35
	case int64:
36
		if n, err := strconv.ParseInt(val, 10, 64); err == nil {
37
			res = n
38
		}
39
	case float64:
40
		if f, err := strconv.ParseFloat(val, 64); err == nil {
41
			res = f
42
		}
43
	case bool:
44
		if b, err := strconv.ParseBool(val); err == nil {
45
			res = b
46
		}
47
	case time.Duration:
48
		if d, err := time.ParseDuration(val); err == nil {
49
			res = d
50
		}
51
	}
52
	return res.(T)
53
}
54
55
// GetOrDefault retrieves an environment variable, if not set, returns default value.
56
// Supported types: string, int, int64, float64, bool, time.Duration.
57
func GetOrDefault[T comparable](key string, def T) T {
58
	var zero T
59
	if val := Get[T](key); val != zero {
60
		return val
61
	}
62
	return def
63
}