package config import ( "errors" "fmt" "os" "strings" "github.com/joho/godotenv" ) // DefaultEnvFile is loaded automatically when it exists. const DefaultEnvFile = ".env" // LoadDotEnv loads KEY=VALUE pairs from the file named by ENV_FILE, or from // .env in the current directory when ENV_FILE is unset. // // Variables that already exist in the process environment are never // overwritten, so exported shell variables take precedence over the file. // A missing default .env is ignored; an explicitly configured ENV_FILE must // exist and be readable. func LoadDotEnv() error { if path := strings.TrimSpace(os.Getenv("ENV_FILE")); path != "" { return LoadEnvFile(path) } if err := godotenv.Load(DefaultEnvFile); err != nil { if errors.Is(err, os.ErrNotExist) { return nil } return fmt.Errorf("load env file %s: %w", DefaultEnvFile, err) } return nil } // LoadEnvFile loads KEY=VALUE pairs from an explicit file. Existing process // variables are not overwritten. The file must exist and be readable. func LoadEnvFile(path string) error { path = strings.TrimSpace(path) if path == "" { return errors.New("env file path must not be empty") } if err := godotenv.Load(path); err != nil { return fmt.Errorf("load env file %s: %w", path, err) } return nil }