Skip to content

Commit

Permalink
Attempt to support SSL for MySQL (#44)
Browse files Browse the repository at this point in the history
* Attempt to support SSL for MySQL

* Should use parameter `tls` for specifying the TLS mode

https://github.com/go-sql-driver/mysql#tls
  • Loading branch information
boris1993 committed Apr 17, 2023
1 parent f153de1 commit bdfbcf0
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 12 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -130,6 +130,8 @@ table: users
# user: root
# password: pwd
# database: e5sub
# ssl_mode is only required when the database requires a SSL connection (e.g. TiDB Cloud)
# ssl_mode: PREFERRED
sqlite:
db: data.db
```
Expand Down
2 changes: 2 additions & 0 deletions README_zhCN.md
Expand Up @@ -126,6 +126,8 @@ table: users
# user: root
# password: pwd
# database: e5sub
# ssl_mode仅在数据库需要SSL链接时才需要配置(如连接TiDB Cloud)
# ssl_mode: PREFERRED
sqlite:
db: data.db
```
Expand Down
12 changes: 7 additions & 5 deletions config/config.go
Expand Up @@ -50,11 +50,13 @@ func Init() {
switch DB {
case "mysql":
Mysql = mysqlConfig{
Host: viper.GetString("mysql.host"),
Port: viper.GetInt("mysql.port"),
User: viper.GetString("mysql.user"),
Password: viper.GetString("mysql.password"),
DB: viper.GetString("mysql.database"),
Host: viper.GetString("mysql.host"),
Port: viper.GetInt("mysql.port"),
User: viper.GetString("mysql.user"),
Password: viper.GetString("mysql.password"),
DB: viper.GetString("mysql.database"),
SSLMode: viper.GetString("mysql.ssl_mode"),
EnabledTLSProtocols: viper.GetString("mysql.enabled_tls_protocols"),
}
case "sqlite":
Sqlite = sqliteConfig{
Expand Down
12 changes: 7 additions & 5 deletions config/model.go
Expand Up @@ -19,9 +19,11 @@ type sqliteConfig struct {
DB string `json:"db,omitempty"`
}
type mysqlConfig struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
DB string `json:"db,omitempty"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
DB string `json:"db,omitempty"`
SSLMode string `json:"ssl_mode,omitempty"`
EnabledTLSProtocols string `json:"enabled_tls_protocols,omitempty"`
}
10 changes: 8 additions & 2 deletions db/db.go
Expand Up @@ -21,13 +21,19 @@ func Init() {

switch config.DB {
case "mysql":
dial = mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
var dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
config.Mysql.User,
config.Mysql.Password,
config.Mysql.Host,
config.Mysql.Port,
config.Mysql.DB,
))
)

if config.Mysql.SSLMode != "" {
dsn += "&tls=" + config.Mysql.SSLMode
}

dial = mysql.Open(dsn)
case "sqlite":
dial = sqlite.Open(config.Sqlite.DB)
}
Expand Down

0 comments on commit bdfbcf0

Please sign in to comment.