feat: add global .env file support from ~/.hrp/.env

- Add support for loading environment variables from ~/.hrp/.env
- Implement priority order: current working directory > ~/.hrp/.env > system environment variables
- Use godotenv.Overload() for both global and local .env files to ensure proper priority
- Maintain backward compatibility with existing functionality
- Add comprehensive error handling and logging
This commit is contained in:
lilong.129
2025-06-02 11:52:36 +08:00
parent 9089bd9324
commit 184081592c
2 changed files with 23 additions and 2 deletions

View File

@@ -15,8 +15,29 @@ var loadEnvOnce sync.Once
// LoadEnv loads environment variables from .env file
// it will search for .env file from current working directory upward recursively
// if not found, it will try to load from ~/.hrp/.env as fallback
// Priority: current working directory > ~/.hrp/.env > system environment variables
func LoadEnv() (err error) {
loadEnvOnce.Do(func() {
// first try to load from ~/.hrp/.env, override system env variables (medium priority)
var homeDir string
homeDir, err = os.UserHomeDir()
if err != nil {
log.Warn().Err(err).Msg("get user home directory failed")
} else {
globalEnvFile := filepath.Join(homeDir, ".hrp", ".env")
if _, e := os.Stat(globalEnvFile); e == nil {
// load global .env file and override system environment variables
err = godotenv.Overload(globalEnvFile)
if err != nil {
log.Error().Err(err).
Str("path", globalEnvFile).Msg("load global env file failed")
return
}
log.Info().Str("path", globalEnvFile).Msg("load global env success")
}
}
// get current working directory
var cwd string
cwd, err = os.Getwd()
@@ -31,7 +52,7 @@ func LoadEnv() (err error) {
envFile := filepath.Join(envPath, ".env")
if _, e := os.Stat(envFile); e == nil {
// found .env file
// override existing env variables
// override existing env variables (highest priority)
err = godotenv.Overload(envFile)
if err != nil {
log.Error().Err(err).

View File

@@ -1 +1 @@
v5.0.0-beta-2505310028
v5.0.0-beta-2506021152