Skip to content

Commit

Permalink
feat: support mysql tls option (merge coaidev#168 from @navee)
Browse files Browse the repository at this point in the history
支持MySql tls连接
  • Loading branch information
zmh-program authored Apr 10, 2024
2 parents 269c3a2 + 8b1c36b commit 72af27b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mysql:
password: chatnio123456
port: 3306
user: root
tls: false

redis:
host: localhost
Expand Down
18 changes: 15 additions & 3 deletions connection/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package connection
import (
"chat/globals"
"chat/utils"
"crypto/tls"
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
Expand Down Expand Up @@ -32,15 +34,25 @@ func getConn() *sql.DB {
return db
}

// connect to MySQL
db, err := sql.Open("mysql", fmt.Sprintf(
mysqlUrl := fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s",
viper.GetString("mysql.user"),
viper.GetString("mysql.password"),
viper.GetString("mysql.host"),
viper.GetInt("mysql.port"),
viper.GetString("mysql.db"),
))
)
if viper.GetBool("mysql.tls") {
mysql.RegisterTLSConfig("tls", &tls.Config{
MinVersion: tls.VersionTLS12,
ServerName: viper.GetString("mysql.host"),
})

mysqlUrl += "?tls=tls"
}

// connect to MySQL
db, err := sql.Open("mysql", mysqlUrl)

if pingErr := db.Ping(); err != nil || pingErr != nil {
errMsg := utils.Multi[string](err != nil, utils.GetError(err), utils.GetError(pingErr)) // err.Error() may contain nil pointer
Expand Down

0 comments on commit 72af27b

Please sign in to comment.