2021-08-20 14:59:13 +08:00
|
|
|
package global
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-08-20 15:15:05 +08:00
|
|
|
. "go_api_tmpl/config"
|
2021-08-20 14:59:13 +08:00
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/logger"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// InitMySQLClient 初始化MySQL连接
|
|
|
|
func InitMySQLClient() {
|
2021-08-20 15:15:05 +08:00
|
|
|
// 初始化MySQL配置
|
|
|
|
InitMySQLConfig()
|
2021-08-20 14:59:13 +08:00
|
|
|
|
|
|
|
newLogger := logger.New(
|
|
|
|
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
|
|
|
|
logger.Config{
|
|
|
|
SlowThreshold: time.Second, // Slow SQL threshold
|
|
|
|
LogLevel: logger.Info, // Log level
|
|
|
|
Colorful: true, // Disable color
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2021-08-20 15:15:05 +08:00
|
|
|
url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
|
|
|
MySQLConfig.Username, MySQLConfig.Password, MySQLConfig.Host, MySQLConfig.Port, MySQLConfig.DbName)
|
2021-08-20 14:59:13 +08:00
|
|
|
conn, err := gorm.Open(mysql.Open(url), &gorm.Config{Logger: newLogger})
|
|
|
|
if err != nil {
|
|
|
|
Log.Panicf("初始化MySQL连接失败, 错误信息: %v", err)
|
|
|
|
}
|
|
|
|
MySQLConn = conn
|
|
|
|
}
|