Files
go-core/dotenv/dotenv.go
2026-03-01 03:04:10 +01:00

53 lines
950 B
Go

package config
import (
"bufio"
"os"
"strings"
)
// LoadDotEnvCandidates loads KEY=VALUE pairs from the first existing file in paths.
// Existing process env vars are preserved (file values only fill missing keys).
func LoadDotEnvCandidates(paths []string) {
for _, path := range paths {
if loadDotEnvFile(path) {
return
}
}
}
func loadDotEnvFile(path string) bool {
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
value = strings.TrimSpace(value)
value = strings.Trim(value, `"'`)
if key == "" {
continue
}
if _, exists := os.LookupEnv(key); exists {
continue
}
_ = os.Setenv(key, value)
}
return true
}