feat(database): 添加数据库连接初始化和ORM支持

- 实现MySQL和SQLite数据库连接初始化功能
- 集成GORM ORM框架支持
- 添加数据库连接状态检测和错误处理
- 实现数据库自动迁移功能
- 添加字段重命名和删除功能
- 更新配置文件以支持数据库类型选择
- 添加TCP服务器示例代码
- 添加WebSocket服务示例代码
- 集成MQTT客户端功能
- 更新项目依赖包列表
This commit is contained in:
2026-02-02 17:48:40 +08:00
parent 6036b00a9b
commit e6d3272e70
15 changed files with 1406 additions and 62 deletions
+22 -16
View File
@@ -7,6 +7,7 @@ import (
"git.magicany.cc/black1552/gin-base/log"
"git.magicany.cc/black1552/gin-base/utils"
"github.com/fsnotify/fsnotify"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/os/gfile"
"github.com/spf13/viper"
@@ -35,22 +36,29 @@ func init() {
return
}
log.Info("配置文件是否为空", utils.EmptyFile(configPath))
setDefault()
SetDefault()
err = viper.WriteConfig()
if err != nil {
log.Error("保存配置文件失败: ", err)
return
}
} else {
err = viper.ReadInConfig()
if err != nil {
log.Error("读取配置文件失败: ", err)
return
}
}
viper.OnConfigChange(func(in fsnotify.Event) {
log.Info("配置文件已修改")
})
}
func setDefault() {
func SetDefault() {
viper.Set("SERVER.addr", "127.0.0.1:8080")
viper.Set("DATABASE.host", "127.0.0.1")
viper.Set("DATABASE.port", 3306)
viper.Set("DATABASE.username", "root")
viper.Set("DATABASE.password", "")
viper.Set("DATABASE.name", "")
viper.Set("SERVER.mode", "release")
viper.Set("DATABASE.type", "mysql")
viper.Set("DATABASE.dns", "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local")
viper.Set("JWT.secret", "SET-YOUR-SECRET")
viper.Set("JWT.expire", 86400)
}
@@ -88,18 +96,16 @@ func SetConfigMap(value map[string]any) error {
}
func GetConfigValue(key string, def ...any) *gvar.Var {
va := gvar.New(viper.Get(key))
if va.IsEmpty() && len(def) > 0 {
value := gvar.New(viper.Get(key))
if value.IsEmpty() && len(def) > 0 {
return gvar.New(def[0])
}
return va
return value
}
func Unmarshal(s any) (any, error) {
err := viper.Unmarshal(s)
if err != nil {
return nil, err
}
return s, nil
func Unmarshal[T any]() (*T, error) {
var s T
err := viper.Unmarshal(&s)
return &s, err
}
func GetAllConfig() map[string]any {
+9 -17
View File
@@ -1,29 +1,21 @@
package config
type BaseConfig struct {
Server ServerConfig `toml:"SERVER"`
Database DataBaseConfig `toml:"DATABASE"`
Jwt JwtConfig `toml:"JWT"`
Logger Logger `toml:"LOGGER"`
Server ServerConfig `mapstructure:"SERVER"`
Database DataBaseConfig `mapstructure:"DATABASE"`
Jwt JwtConfig `mapstructure:"JWT"`
}
type ServerConfig struct {
Addr string `toml:"addr"`
Addr string `mapstructure:"addr"`
Mode string `mapstructure:"mode"`
}
type DataBaseConfig struct {
Host string `toml:"host"`
Port string `toml:"port"`
User string `toml:"user"`
Pwd string `toml:"pwd"`
Name string `toml:"name"`
Dns string `mapstructure:"dns"`
Type string `mapstructure:"type"`
}
type JwtConfig struct {
Secret string `toml:"secret"`
Expire int64 `toml:"expire"`
}
type Logger struct {
Level string `toml:"level"`
Path string `toml:"path"`
Secret string `mapstructure:"secret"`
Expire int64 `mapstructure:"expire"`
}