Compare commits

...

3 Commits

Author SHA1 Message Date
44319d03b9 ```
refactor(database): 移除全局初始化函数定义

将数据库初始化函数从 database 包中移除,避免全局状态污染。

feat(service): 新增 Use 方法用于执行初始化函数

在 Service 结构体中添加 Use 方法,允许传入并执行初始化函数。
如果函数执行失败,则打印错误并 panic。

refactor(with): 删除旧的初始化逻辑包

删除 with 包中与数据库初始化相关的旧逻辑,统一初始化入口。
```
2025-09-23 12:37:00 +08:00
2f57edd277 ```
refactor(database): 重构数据库初始化逻辑

移除 NewDatabase 函数中的 Init 参数,改用 InitFunc 变量进行初始化操作。
更新 MigrateTables 附近的注释,明确说明 InitFunc 的用途。
删除函数内对 Init 参数的执行逻辑,确保代码简洁性。
```
2025-09-23 11:28:33 +08:00
cf0ee224f7 ```
refactor(database): 调整数据库初始化函数参数传递方式

将 Init 函数参数从全局变量改为通过 NewDatabase 函数参数传入,
使初始化逻辑更清晰、可控。同时优化代码格式,去除多余空行,
提升代码可读性。
```
2025-09-23 11:02:25 +08:00
3 changed files with 17 additions and 13 deletions

View File

@@ -118,12 +118,12 @@ func PKCS7UnPadding(origData []byte, blocksize int) []byte {
if blocksize <= 0 {
return nil
}
// 检查原始数据是否为空
if origData == nil || len(origData) == 0 {
return nil
}
// 检查数据长度是否为块大小的整数倍
if len(origData)%blocksize != 0 {
return nil
@@ -137,7 +137,7 @@ func PKCS7UnPadding(origData []byte, blocksize int) []byte {
if length-unpadding <= 0 {
return nil
}
// 返回去除填充后的数据
return origData[:(length - unpadding)]
}

View File

@@ -15,8 +15,6 @@ import (
var (
// MigrateTables holds the tables that need to be auto-migrated on database initialization
MigrateTables []any
// Init is an optional initialization function that can be executed after database connection is established
Init *func() = nil
)
// NewDatabase creates a new database connection based on the provided driver type
@@ -36,11 +34,6 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *go
return nil, err
}
// Execute the Init function if it's not nil
if Init != nil {
(*Init)()
}
return db, nil
}
@@ -73,7 +66,7 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
@@ -118,7 +111,7 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
@@ -134,4 +127,4 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
}
return
}
}

View File

@@ -108,6 +108,17 @@ func (s *Service) Gateway(grpcAddr string, httpAddr string) {
http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
}
func (s *Service) Use(initFunc *func() error) {
// Execute the Init function if it's not nil
if initFunc != nil {
err := (*initFunc)()
if err != nil {
print.Error(err.Error())
panic(err)
}
}
}
func (s *Service) Stop() {
s.GrpcSrv.GracefulStop()
}