From 44319d03b9911ffda196d8770ed4d1829eb30e5b Mon Sep 17 00:00:00 2001 From: yanweidong Date: Tue, 23 Sep 2025 12:37:00 +0800 Subject: [PATCH] =?UTF-8?q?```=20refactor(database):=20=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=A8=E5=B1=80=E5=88=9D=E5=A7=8B=E5=8C=96=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将数据库初始化函数从 database 包中移除,避免全局状态污染。 feat(service): 新增 Use 方法用于执行初始化函数 在 Service 结构体中添加 Use 方法,允许传入并执行初始化函数。 如果函数执行失败,则打印错误并 panic。 refactor(with): 删除旧的初始化逻辑包 删除 with 包中与数据库初始化相关的旧逻辑,统一初始化入口。 ``` --- database/new.go | 2 -- service/service.go | 11 +++++++++++ with/init.go | 18 ------------------ 3 files changed, 11 insertions(+), 20 deletions(-) delete mode 100644 with/init.go diff --git a/database/new.go b/database/new.go index 4baf740..815fbd6 100644 --- a/database/new.go +++ b/database/new.go @@ -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 - InitFunc *func() error = nil ) // NewDatabase creates a new database connection based on the provided driver type diff --git a/service/service.go b/service/service.go index b7aafff..19b1aa6 100644 --- a/service/service.go +++ b/service/service.go @@ -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() } diff --git a/with/init.go b/with/init.go deleted file mode 100644 index 1b60b68..0000000 --- a/with/init.go +++ /dev/null @@ -1,18 +0,0 @@ -package with - -import ( - "git.apinb.com/bsm-sdk/core/database" - "git.apinb.com/bsm-sdk/core/errcode" - "git.apinb.com/bsm-sdk/core/print" -) - -func InitData() { - // Execute the Init function if it's not nil - if database.InitFunc != nil { - err := (*database.InitFunc)() - if err != nil { - print.Error(errcode.ErrEtcd.Error()) - panic(err) - } - } -}