chore: 重构数据库迁移与 nginx 配置目录

This commit is contained in:
2026-06-24 21:58:50 +08:00
parent 0d8377c2fd
commit 5e0c1dd2c1
11 changed files with 91 additions and 45 deletions

View File

@@ -4,12 +4,40 @@ import (
"fmt"
"log"
"os"
"strings"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// loadDotEnv 在当前工作目录查找 .env 文件并加载到进程环境变量中(已存在的变量不覆盖)。
// 仅用于本地开发场景:生产部署通过 docker-compose / 容器环境变量直接注入,没有 .env 文件时静默跳过。
func loadDotEnv() {
data, err := os.ReadFile(".env")
if err != nil {
return
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
if key == "" {
continue
}
if _, exists := os.LookupEnv(key); exists {
continue
}
os.Setenv(key, strings.TrimSpace(value))
}
}
// DBConfig holds MySQL connection parameters.
type DBConfig struct {
Host string
@@ -24,39 +52,42 @@ func (c DBConfig) DSN() string {
c.User, c.Password, c.Host, c.Port, c.DBName)
}
func devConfig() DBConfig {
return DBConfig{
Host: "10.1.1.100",
Port: "3306",
User: "sproutgate-test",
Password: "sproutgate-test",
DBName: "sproutgate-test",
// envConfig 从环境变量读取连接参数。Host/User/Password 没有内置默认值,必须由
// 部署环境(本地 shell、.env、docker-compose 等显式提供DBName 默认统一为
// "sproutgate",开发和生产环境共用同一个库名。
func envConfig() (DBConfig, error) {
host := os.Getenv("DB_HOST")
user := os.Getenv("DB_USER")
password := os.Getenv("DB_PASSWORD")
if host == "" || user == "" || password == "" {
return DBConfig{}, fmt.Errorf("缺少数据库环境变量,请设置 DB_HOST/DB_USER/DB_PASSWORD或直接设置 DB_DSN")
}
}
func prodConfig() DBConfig {
return DBConfig{
Host: "192.168.1.100",
Port: "3306",
User: "sproutgate",
Password: "sproutgate",
DBName: "sproutgate",
port := os.Getenv("DB_PORT")
if port == "" {
port = "3306"
}
dbName := os.Getenv("DB_NAME")
if dbName == "" {
dbName = "sproutgate"
}
return DBConfig{Host: host, Port: port, User: user, Password: password, DBName: dbName}, nil
}
// Open 根据环境变量打开数据库连接。
// 优先级DB_DSN > APP_ENV(production/prod -> 生产库) > 默认开发库
// 优先级DB_DSN(完整自定义连接串)> DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME
func Open() (*gorm.DB, error) {
loadDotEnv()
dsn := os.Getenv("DB_DSN")
if dsn == "" {
env := os.Getenv("APP_ENV")
if env == "production" || env == "prod" {
dsn = prodConfig().DSN()
log.Println("[database] 使用生产数据库 192.168.1.100:3306/sproutgate")
} else {
dsn = devConfig().DSN()
log.Println("[database] 使用开发数据库 10.1.1.100:3306/sproutgate-test")
cfg, err := envConfig()
if err != nil {
return nil, err
}
dsn = cfg.DSN()
log.Printf("[database] 使用数据库 %s:%s/%s", cfg.Host, cfg.Port, cfg.DBName)
} else {
log.Println("[database] 使用自定义 DB_DSN")
}