feat 添加默认加载数据库的方法
This commit is contained in:
parent
f53ff1cc7f
commit
db0310a6a0
@ -2,12 +2,40 @@ package database
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
func InitDatabase(opt *DBOption) (*gorm.DB, error) {
|
func InitDatabase(opt *DBOption) (*gorm.DB, error) {
|
||||||
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", opt.Host, opt.User, opt.Password, opt.DBName, opt.Port)
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", opt.Host, opt.User, opt.Password, opt.DBName, opt.Port)
|
||||||
return gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
return gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func InitDefaultDatabase() (*gorm.DB, error) {
|
||||||
|
path := os.Getenv(ConfigPathEnvKey)
|
||||||
|
if path != "" {
|
||||||
|
path = DefaultConfigPath
|
||||||
|
}
|
||||||
|
cfg, err := LoadDBConfig(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("获取数据库配置失败:%v", err)
|
||||||
|
}
|
||||||
|
db, err := InitDatabase(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("初始化数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
db.Logger = logger.New(
|
||||||
|
log.New(os.Stdout, "\r\n", log.LstdFlags),
|
||||||
|
logger.Config{
|
||||||
|
SlowThreshold: time.Second,
|
||||||
|
LogLevel: logger.Warn,
|
||||||
|
Colorful: true,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user