refactor: 解决无法正确加载 .env 的问题

This commit is contained in:
2026-04-20 15:54:40 +08:00
parent 181edf418e
commit d967e74125
2 changed files with 47 additions and 5 deletions
+24 -5
View File
@@ -3,6 +3,8 @@ package config
import (
"fmt"
"os"
"path/filepath"
"runtime"
"time"
"github.com/gin-contrib/cors"
@@ -48,13 +50,30 @@ type Config struct {
}
func Load() (*Config, error) {
var err error
err = godotenv.Load("../configs/.env")
err = godotenv.Load("./configs/.env")
if err != nil {
return nil, fmt.Errorf("error loading .env file: %w", err)
// 查找go.mod所在的模块根目录
_, filename, _, ok := runtime.Caller(0)
if !ok {
return nil, fmt.Errorf("unable to get caller info")
}
dir := filepath.Dir(filename)
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
// 找到模块根目录,加载configs/.env
envPath := filepath.Join(dir, "configs", ".env")
if err = godotenv.Load(envPath); err == nil {
break
}
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
// 如果找不到.env,继续使用环境变量
cfg := &Config{
Server: ServerConfig{
Port: getEnv("PORT", "3001"),
+23
View File
@@ -0,0 +1,23 @@
package config
import (
"testing"
)
func TestLoad(t *testing.T) {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() failed: %v", err)
}
if cfg.Server.Port == "" {
t.Error("Expected Server.Port to have default value")
}
if cfg.LLM.Provider == "" && cfg.LLM.APIKey == "" {
t.Logf("Config loaded - some optional values may be empty (expected if .env not found)")
} else {
t.Logf("Config loaded successfully. Provider: %s, Model: %s",
cfg.LLM.Provider, cfg.LLM.Model)
}
}