From c169f99b616eaa67323ab89337b26de9afafa8da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=AF=BB=E6=AC=A2?= <1101766085@qq.com> Date: Mon, 23 Aug 2021 03:57:00 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20=E4=BC=98=E5=8C=96=20MySQL=20?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=94=9F=E6=88=90?= =?UTF-8?q?=E8=A7=84=E5=88=99(=E6=96=B9=E4=BE=BF=E5=90=8E=E9=9D=A2=20OAuth?= =?UTF-8?q?2=20=E5=A4=8D=E7=94=A8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- config/mysql.go | 8 ++++++++ global/mysql.go | 5 +---- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 20d3308..b193604 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .idea vendor -logs \ No newline at end of file +logs +*.db \ No newline at end of file diff --git a/config/mysql.go b/config/mysql.go index f120f2d..2d7bec1 100644 --- a/config/mysql.go +++ b/config/mysql.go @@ -1,5 +1,7 @@ package config +import "fmt" + // MySQL配置 type mysqlConfig struct { Host string // 主机 @@ -25,3 +27,9 @@ func InitMySQLConfig() { DbName: dbName, } } + +// GetDSN 返回 MySQL 连接字符串 +func (c mysqlConfig) GetDSN() string { + return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", + c.Username, c.Password, c.Host, c.Port, c.DbName) +} diff --git a/global/mysql.go b/global/mysql.go index 428d643..2ff7d8f 100644 --- a/global/mysql.go +++ b/global/mysql.go @@ -1,7 +1,6 @@ package global import ( - "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" @@ -25,9 +24,7 @@ func InitMySQLClient() { }, ) - 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) - conn, err := gorm.Open(mysql.Open(url), &gorm.Config{Logger: newLogger}) + conn, err := gorm.Open(mysql.Open(MySQLConfig.GetDSN()), &gorm.Config{Logger: newLogger}) if err != nil { Log.Panicf("初始化MySQL连接失败, 错误信息: %v", err) }