-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenv.go
79 lines (71 loc) · 1.73 KB
/
env.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"github.com/joho/godotenv"
"log/slog"
"os"
"strconv"
)
func loadEnvFile() {
if !checkedEnvFile {
if err := godotenv.Load(".env.local", ".env"); err != nil {
slog.Debug(".env file not loaded;", "reason", err)
}
checkedEnvFile = true
}
}
func getEnv(key string, defaultValue interface{}) interface{} {
loadEnvFile()
if value, exists := os.LookupEnv(key); exists {
switch expectedType := defaultValue.(type) {
case int8, int16, int32, int64, int:
if parseInt, err := strconv.ParseInt(value, 10, 64); err == nil {
switch expectedType.(type) {
case int8:
return int8(parseInt)
case int16:
return int16(parseInt)
case int32:
return int32(parseInt)
case int64:
return parseInt
case int:
return int(parseInt)
}
}
case uint8, uint16, uint32, uint64, uint:
if parseUint, err := strconv.ParseUint(value, 10, 64); err == nil {
switch expectedType.(type) {
case uint8:
return uint8(parseUint)
case uint16:
return uint16(parseUint)
case uint32:
return uint32(parseUint)
case uint64:
return parseUint
case uint:
return uint(parseUint)
}
}
case float32, float64:
if parseFloat, err := strconv.ParseFloat(value, 64); err == nil {
switch expectedType.(type) {
case float32:
return float32(parseFloat)
case float64:
return parseFloat
}
}
case bool:
if parseBool, err := strconv.ParseBool(value); err == nil {
return parseBool
}
case string:
return value
}
slog.Info("Unexpected value for env key, falling back to default;", "key", key, "value", value, "defaultValue", defaultValue)
}
return defaultValue
}
// one time check for .env file
var checkedEnvFile = false