all repos

x @ 6c0a72ea3d6f353d25a7b954c6ded067ddf529c8

go extra()

x/envy/env.go(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 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
}