- 实现数据库连接和自动迁移 - 实现用户服务(登录、资料、JWT认证) - 实现许愿服务(创建、列表、机器人许愿) - 实现订单服务(创建、支付、状态管理) - 实现JWT认证中间件 - 实现管理后台API(仪表盘、用户、订单、许愿、设置) - 创建Inertia.js前端页面(Vue3 + Tailwind CSS) - 修复Go模块依赖问题
56 lines
1.0 KiB
Go
56 lines
1.0 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
"github.com/gouki/lunar-server/internal/model"
|
|
)
|
|
|
|
var DB *gorm.DB
|
|
|
|
// InitDB 初始化数据库连接
|
|
func InitDB(cfg *Config) error {
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
|
cfg.Database.User,
|
|
cfg.Database.Password,
|
|
cfg.Database.Host,
|
|
cfg.Database.Port,
|
|
cfg.Database.Name,
|
|
)
|
|
|
|
var err error
|
|
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to connect database: %w", err)
|
|
}
|
|
|
|
// 自动迁移
|
|
if err := autoMigrate(); err != nil {
|
|
return fmt.Errorf("failed to migrate database: %w", err)
|
|
}
|
|
|
|
log.Println("Database connected and migrated successfully")
|
|
return nil
|
|
}
|
|
|
|
// autoMigrate 自动迁移数据库表
|
|
func autoMigrate() error {
|
|
return DB.AutoMigrate(
|
|
&model.User{},
|
|
&model.UserProfile{},
|
|
&model.Order{},
|
|
&model.OrderItem{},
|
|
&model.WishTree{},
|
|
&model.Wish{},
|
|
&model.WishProduct{},
|
|
)
|
|
}
|
|
|
|
// GetDB 获取数据库连接
|
|
func GetDB() *gorm.DB {
|
|
return DB
|
|
}
|