Files
2026-05-27 08:18:36 +08:00

52 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package forward
import (
"log"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
// LoadEnvFiles 从多个候选路径加载 .env不覆盖已存在的 OS 环境变量)。
// 查找顺序:当前工作目录 → 可执行文件目录 → 可执行文件上级目录。
func LoadEnvFiles() bool {
candidates := envFileCandidates()
for _, p := range candidates {
// 步骤 1路径不存在则尝试下一个候选
if _, err := os.Stat(p); err != nil {
continue
}
// 步骤 2加载成功即返回godotenv 不覆盖已有环境变量)
if err := godotenv.Load(p); err != nil {
log.Printf("[forward] 加载 %s 失败: %v", p, err)
continue
}
log.Printf("[forward] 已加载 %s", p)
return true
}
log.Print("[forward] 未找到 .env将使用环境变量或代码默认值请复制 .env.example 为 .env 并配置 SUPERVISE_TARGET_URL / FILE_TARGET_URL")
return false
}
// envFileCandidates 生成 .env 候选路径列表(去重)。
func envFileCandidates() []string {
seen := make(map[string]struct{})
var out []string
add := func(p string) {
p = filepath.Clean(p)
if _, ok := seen[p]; ok {
return
}
seen[p] = struct{}{}
out = append(out, p)
}
if wd, err := os.Getwd(); err == nil && wd != "" {
add(filepath.Join(wd, ".env"))
}
base := programDir()
add(filepath.Join(base, ".env"))
add(filepath.Join(base, "..", ".env"))
return out
}