feat: 引入多环境配置支持,通过 .env.dev 和 .env.prod 文件管理不同环境配置,并更新 main.go 以加载对应配置。
This commit is contained in:
@@ -20,19 +20,37 @@ import (
|
||||
func main() {
|
||||
// Load .env file from project root (try multiple locations)
|
||||
envPaths := []string{
|
||||
".env", // Current directory
|
||||
"../.env", // Parent directory (when running from backend/)
|
||||
"../../.env", // Two levels up (when running from backend/cmd/server/)
|
||||
".env", // Current directory
|
||||
"../.env", // Parent directory (when running from backend/)
|
||||
"../../.env", // Two levels up (when running from backend/cmd/server/)
|
||||
filepath.Join("..", "..", ".env"), // Explicit path
|
||||
}
|
||||
|
||||
|
||||
var envDir string
|
||||
for _, envPath := range envPaths {
|
||||
if err := godotenv.Load(envPath); err == nil {
|
||||
log.Printf("Loaded environment from: %s", envPath)
|
||||
log.Printf("Loaded base environment from: %s", envPath)
|
||||
envDir = filepath.Dir(envPath)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Load specific environment file if APP_ENV is set (e.g. .env.dev, .env.prod)
|
||||
// This allows switching environments by just changing APP_ENV in .env
|
||||
if appEnv := os.Getenv("APP_ENV"); appEnv != "" {
|
||||
targetEnvFile := ".env." + appEnv
|
||||
targetEnvPath := targetEnvFile
|
||||
if envDir != "" && envDir != "." {
|
||||
targetEnvPath = filepath.Join(envDir, targetEnvFile)
|
||||
}
|
||||
|
||||
if err := godotenv.Overload(targetEnvPath); err == nil {
|
||||
log.Printf("Loaded specific environment config from: %s", targetEnvPath)
|
||||
} else {
|
||||
log.Printf("Note: Specific environment file %s not found or could not be loaded", targetEnvPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Load configuration
|
||||
cfg := config.Load()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user