添加 数据库/表结构同步配置

添加 数据库/表结构同步
This commit is contained in:
Shikong 2022-10-04 01:46:48 +08:00
parent cd33f1e307
commit 64ac1d1f45
4 changed files with 53 additions and 7 deletions

17
app.go
View File

@ -38,8 +38,14 @@ func reloadDataSources(c *config.BasicConfig) {
if err != nil {
logger.Log.Fatalf("[x] [数据源] 致命错误: %s", err)
}
logger.Log.Infoln("[√] [初始化数据源]")
global.DataSources = connGroup
if c.Mysql.AutoSync {
global.SyncModelToDataSource()
}
}
func reloadApp(c *config.BasicConfig) *fiber.App {
@ -68,12 +74,19 @@ func reloadApp(c *config.BasicConfig) *fiber.App {
},
})
routes(app)
if c.Server.EnableRoutesMsg {
routes(app)
}
controller.SwaggerHandler(app)
controller.HelloWorld(app)
controller.ErrorHandler(app)
logger.Log.Infoln("[√] [服务启动完成]")
app.Hooks().OnListen(func() error {
logger.Log.Infoln("[√] [服务启动完成]")
return nil
})
return app
}

View File

@ -2,10 +2,12 @@ package config
type BasicConfig struct {
Server ServerConfig `yaml:"server"`
Mysql MysqlConfig `yaml:"mysql"`
}
Mysql struct {
DataSources []string `yaml:"dataSources"`
} `yaml:"mysql"`
type MysqlConfig struct {
DataSources []string `yaml:"dataSources"`
AutoSync bool `yaml:"autoSync"`
}
type ServerConfig struct {
@ -19,6 +21,8 @@ type ServerConfig struct {
StrictRouting bool `yaml:"strictRouting"`
// 设置 Http 请求头中的 Server 名称
ServerHeader string `yaml:"serverHeader"`
// 是否添加 /routes 路由 用于获取所有路由信息
EnableRoutesMsg bool `yaml:"enableRoutesMsg"`
}
type RedisConfig struct {

View File

@ -1,10 +1,20 @@
server:
# 监听地址 :3000 或 127.0.0.1:3000
addr: ":3000"
preFork: true
# 启用多进程
preFork: false
# 路由大小写严格
caseSensitive: true
# 严格路由模式
strictRouting: false
# 服务器名称
serverHeader: SkServer
# 启用路由信息 /routes
enableRoutesMsg: true
mysql:
# 自动同步数据库/表结构
autoSync: true
# 数据源 参考 xorm 数据源配置
dataSources:
- root:12341234@tcp(10.10.10.100:3306)/gofiber?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

View File

@ -1,5 +1,24 @@
package global
import "xorm.io/xorm"
import (
"gofiber.study.skcks.cn/common/logger"
"gofiber.study.skcks.cn/model/user/models"
"xorm.io/xorm"
"xorm.io/xorm/names"
)
var DataSources *xorm.EngineGroup
func SyncModelToDataSource() {
modelArr := []interface{ names.TableName }{&models.User{}}
logger.Log.Infof("[*] 同步数据库/表结构")
for _, model := range modelArr {
err := DataSources.Sync(model)
logger.Log.Infof("[√] 同步 %s 表 数据结构 成功", model.TableName())
if err != nil {
logger.Log.Fatalf("[x] 同步 %s 表 数据结构时出错: %s", model.TableName(), err)
}
}
}