From 4971a06799721e3adb4c052ae5ba48043cbba234 Mon Sep 17 00:00:00 2001 From: labulac <740162752@qq.com> Date: Wed, 29 Mar 2023 11:18:10 +0800 Subject: [PATCH] Add mysql TLS Support Change: Use DSN custom configuration instead of using specific configuration options. --- conf/config.yaml | 7 +------ config/model.go | 8 +++----- dal/dal.go | 9 +++------ 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/conf/config.yaml b/conf/config.yaml index 0d337c2..9bd6bf7 100644 --- a/conf/config.yaml +++ b/conf/config.yaml @@ -19,12 +19,7 @@ sqlite3: mysql: - host: 127.0.0.1 - port: 3306 - db: sonicdb - username: "root" - password: "12345678" - + dsn: username:password@tcp(host:port)/db_name?charset=utf8mb4&parseTime=True&loc=Local&interpolateParams=true sonic: mode: "production" diff --git a/config/model.go b/config/model.go index 5d3d81f..755fcfa 100644 --- a/config/model.go +++ b/config/model.go @@ -16,13 +16,11 @@ type PostgreSQL struct { Username string `mapstructure:"username"` Password string `mapstructure:"password"` } + type MySQL struct { - Host string `mapstructure:"host"` - Port string `mapstructure:"port"` - DB string `mapstructure:"db"` - Username string `mapstructure:"username"` - Password string `mapstructure:"password"` + Dsn string `mapstructure:"dsn"` } + type SQLite3 struct { Enable bool `mapstructure:"enable"` File string diff --git a/dal/dal.go b/dal/dal.go index ec0b01e..5589bd9 100644 --- a/dal/dal.go +++ b/dal/dal.go @@ -2,7 +2,6 @@ package dal import ( "context" - "fmt" "time" "go.uber.org/zap" @@ -18,9 +17,6 @@ import ( "github.com/go-sonic/sonic/util/xerr" ) -// mysqlDsn example user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local -const mysqlDsn = "%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=1s&writeTimeout=1s&interpolateParams=true" - var ( DB *gorm.DB DBType consts.DBType @@ -66,8 +62,9 @@ func initMySQL(conf *config.Config, gormLogger logger.Interface) (*gorm.DB, erro if mysqlConfig == nil { return nil, xerr.WithMsg(nil, "nil MySQL config") } - dsn := fmt.Sprintf(mysqlDsn, mysqlConfig.Username, mysqlConfig.Password, mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.DB) - sonicLog.Info("try connect to MySQL", zap.String("dsn", fmt.Sprintf(mysqlDsn, mysqlConfig.Username, "***", mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.DB))) + dsn := mysqlConfig.Dsn + + sonicLog.Info("try connect to MySQL", zap.String("dsn", `Use dsn in config`)) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: gormLogger, PrepareStmt: true,