初步搭建02

This commit is contained in:
des
2026-01-13 13:02:27 +08:00
parent 0c68d57180
commit a289a90676
3 changed files with 45 additions and 19 deletions

View File

@@ -1,11 +1,18 @@
package common
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func GetDataBaseClient() *gorm.DB {
// GetDataBaseClient 获取数据库链接
//
// 返回值
// - 一个 gorm.DB 的指针
// - 一个清理所有数据库相关数据的函数
func GetDataBaseClient() (*gorm.DB, func() error) {
dsn := "host=localhost " +
"user=gatekeeper " +
"dbname=crimson " +
@@ -13,9 +20,21 @@ func GetDataBaseClient() *gorm.DB {
"port=5432 " +
"password=crimson " +
"connect_timeout=20 "
client, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("无法连接数据库")
client, ero := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if ero != nil {
fmt.Println("数据库链接建立失败")
panic(ero)
}
return client
poolCfg, ero := client.DB()
if ero != nil {
fmt.Println("获取数据库链接池失败")
panic(ero)
}
poolCfg.SetConnMaxIdleTime(3)
poolCfg.SetMaxOpenConns(10)
return client, poolCfg.Close
}