| 1 | // Package config holds tiny env helpers shared by andromeda Go apps. |
| 2 | package config |
| 3 | |
| 4 | import ( |
| 5 | "os" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // Getenv returns the trimmed value of key or fallback when unset/blank. |
| 11 | func Getenv(key, fallback string) string { |
| 12 | if v := strings.TrimSpace(os.Getenv(key)); v != "" { |
| 13 | return v |
| 14 | } |
| 15 | return fallback |
| 16 | } |
| 17 | |
| 18 | // GetenvInt parses key as int or returns fallback. |
| 19 | func GetenvInt(key string, fallback int) int { |
| 20 | if v, err := strconv.Atoi(strings.TrimSpace(os.Getenv(key))); err == nil { |
| 21 | return v |
| 22 | } |
| 23 | return fallback |
| 24 | } |
| 25 | |
| 26 | // GetenvBool returns true for "true"/"1"/"yes" (case-insensitive), false for the |
| 27 | // matching negatives, and fallback otherwise. |
| 28 | func GetenvBool(key string, fallback bool) bool { |
| 29 | v := strings.TrimSpace(os.Getenv(key)) |
| 30 | switch strings.ToLower(v) { |
| 31 | case "true", "1", "yes", "on": |
| 32 | return true |
| 33 | case "false", "0", "no", "off": |
| 34 | return false |
| 35 | } |
| 36 | return fallback |
| 37 | } |
| 38 | |
| 39 | // LoadDotEnv reads a KEY=VALUE file and populates os.Environ for keys not |
| 40 | // already set. Missing files are silently ignored. |
| 41 | func LoadDotEnv(path string) { |
| 42 | data, err := os.ReadFile(path) |
| 43 | if err != nil { |
| 44 | return |
| 45 | } |
| 46 | for _, line := range strings.Split(string(data), "\n") { |
| 47 | line = strings.TrimSpace(line) |
| 48 | if line == "" || strings.HasPrefix(line, "#") || !strings.Contains(line, "=") { |
| 49 | continue |
| 50 | } |
| 51 | parts := strings.SplitN(line, "=", 2) |
| 52 | key := strings.TrimSpace(parts[0]) |
| 53 | val := strings.Trim(strings.TrimSpace(parts[1]), `"'`) |
| 54 | if os.Getenv(key) == "" { |
| 55 | _ = os.Setenv(key, val) |
| 56 | } |
| 57 | } |
| 58 | } |