From cf0ee224f7c50843d77c519d3de97e2a57498b3e Mon Sep 17 00:00:00 2001 From: yanweidong Date: Tue, 23 Sep 2025 11:02:25 +0800 Subject: [PATCH] =?UTF-8?q?```=20refactor(database):=20=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E5=88=9D=E5=A7=8B=E5=8C=96=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E5=8F=82=E6=95=B0=E4=BC=A0=E9=80=92=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 Init 函数参数从全局变量改为通过 NewDatabase 函数参数传入, 使初始化逻辑更清晰、可控。同时优化代码格式,去除多余空行, 提升代码可读性。 ``` --- crypto/encipher/encipher.go | 6 +++--- database/new.go | 10 ++++------ 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/crypto/encipher/encipher.go b/crypto/encipher/encipher.go index 1cc02f9..c14c028 100644 --- a/crypto/encipher/encipher.go +++ b/crypto/encipher/encipher.go @@ -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)] } diff --git a/database/new.go b/database/new.go index a9c55ea..1d0fd19 100644 --- a/database/new.go +++ b/database/new.go @@ -15,13 +15,11 @@ 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 // It supports both MySQL and PostgreSQL databases -func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *gorm.DB, err error) { +func NewDatabase(driver string, dsn []string, options *types.SqlOptions, Init *func()) (db *gorm.DB, err error) { driver = strings.ToLower(driver) switch driver { case "mysql": @@ -73,7 +71,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 +116,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 +132,4 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err } return -} \ No newline at end of file +}