feat(config): 添加环境变量加载功能
新增 LoadEnv 函数用于从 .env.local 文件加载环境变量 支持从多个路径查找配置文件
This commit is contained in:
parent
ff0f02f065
commit
b7c194be4b
Binary file not shown.
|
|
@ -101,3 +101,38 @@ func (d DB) DSN() string {
|
||||||
}
|
}
|
||||||
return d.User + ":" + d.Password + "@tcp(" + d.Host + ":" + d.Port + ")/" + d.Name + "?parseTime=True&loc=Local&charset=utf8mb4"
|
return d.User + ":" + d.Password + "@tcp(" + d.Host + ":" + d.Port + ")/" + d.Name + "?parseTime=True&loc=Local&charset=utf8mb4"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func LoadEnv() {
|
||||||
|
paths := []string{
|
||||||
|
".env.local",
|
||||||
|
filepath.Join("server", ".env.local"),
|
||||||
|
}
|
||||||
|
for _, p := range paths {
|
||||||
|
f, err := os.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(f)
|
||||||
|
f.Close()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
lines := strings.Split(string(b), "\n")
|
||||||
|
for _, ln := range lines {
|
||||||
|
s := strings.TrimSpace(ln)
|
||||||
|
if s == "" || strings.HasPrefix(s, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kv := strings.SplitN(s, "=", 2)
|
||||||
|
if len(kv) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
k := strings.TrimSpace(kv[0])
|
||||||
|
v := strings.TrimSpace(kv[1])
|
||||||
|
if k != "" {
|
||||||
|
os.Setenv(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -138,3 +138,5 @@ server listening on :8077
|
||||||
{"bytes":2075,"duration_ms":44,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:02+08:00"}
|
{"bytes":2075,"duration_ms":44,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:02+08:00"}
|
||||||
{"bytes":2075,"duration_ms":47,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:04+08:00"}
|
{"bytes":2075,"duration_ms":47,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:04+08:00"}
|
||||||
{"bytes":2187,"duration_ms":92,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:10+08:00"}
|
{"bytes":2187,"duration_ms":92,"kind":"access","level":"INFO","method":"","path":"","query":"","remote":"","status":200,"trace_id":"","ts":"2025-11-27T18:38:10+08:00"}
|
||||||
|
connecting YMT MySQL: 47.97.27.195:3306 db merketing user root
|
||||||
|
connecting Marketing MySQL: 192.168.6.92:3306 db market user root
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue