diff --git a/app.go b/app.go index 8c8b1ce..cf35d08 100644 --- a/app.go +++ b/app.go @@ -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 } diff --git a/common/config/config.go b/common/config/config.go index 8926bed..ea04c52 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -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 { diff --git a/config.yaml b/config.yaml index 698e2d1..d438571 100644 --- a/config.yaml +++ b/config.yaml @@ -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 \ No newline at end of file diff --git a/global/datasources.go b/global/datasources.go index 109532b..51b3c21 100644 --- a/global/datasources.go +++ b/global/datasources.go @@ -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) + } + } +}