Files
xk-hy-forward-go/internal/forward/env.go
2026-05-22 08:42:27 +08:00

49 lines
1.1 KiB
Go
Raw 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 环境变量)。
// 查找顺序CWD → programDir → programDir/..
func LoadEnvFiles() bool {
candidates := envFileCandidates()
for _, p := range candidates {
if _, err := os.Stat(p); err != nil {
continue
}
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
}
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
}