如何使用 gorm 创建到 mysql 的 ssl 连接?
How to create ssl connection to mysql with gorm?
似乎找不到任何关于使用 gorm 创建到 mysql 的 SSL 连接的资源。我正在创建这样的非 SSL 连接:
cfg := mysql.Config{
User: config.User,
Passwd: config.Password,
Addr: fmt.Sprintf("%s:%d", config.Host, config.Port),
Net: "tcp",
Params: options,
}
str := cfg.FormatDSN()
db, err := gorm.Open("mysql", str)
在具有 'pem' 文件路径的 Param 选项中传递 'ssl-ca' 选项似乎不起作用。有什么注意事项吗?
这是我的工作代码片段:
isTLS := false
if mysqlClientKey != "" && mysqlCaCert != "" && mysqlClientCert != "" {
isTLS = true
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("/path/mysqlCaCert")
if err != nil {
log.Fatal(err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
log.Fatal("Failed to append PEM.")
}
clientCert := make([]tls.Certificate, 0, 1)
certs, err := tls.LoadX509KeyPair("/path/mysqlClientCert", "/path/mysqlClientKey")
if err != nil {
log.Fatal(err)
}
clientCert = append(clientCert, certs)
mysql.RegisterTLSConfig("custom", &tls.Config{
RootCAs: rootCertPool,
Certificates: clientCert,
})
}
// try to connect to mysql database.
cfg := mysql.Config{
User: username,
Passwd: password,
Addr: server, //IP:PORT
Net: "tcp",
DBName: database,
Loc: time.Local,
AllowNativePasswords: true,
Params: o,
}
if isTLS == true {
cfg.TLSConfig = "custom"
}
str := cfg.FormatDSN()
db, err := gorm.Open("mysql", str)
似乎找不到任何关于使用 gorm 创建到 mysql 的 SSL 连接的资源。我正在创建这样的非 SSL 连接:
cfg := mysql.Config{
User: config.User,
Passwd: config.Password,
Addr: fmt.Sprintf("%s:%d", config.Host, config.Port),
Net: "tcp",
Params: options,
}
str := cfg.FormatDSN()
db, err := gorm.Open("mysql", str)
在具有 'pem' 文件路径的 Param 选项中传递 'ssl-ca' 选项似乎不起作用。有什么注意事项吗?
这是我的工作代码片段:
isTLS := false
if mysqlClientKey != "" && mysqlCaCert != "" && mysqlClientCert != "" {
isTLS = true
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("/path/mysqlCaCert")
if err != nil {
log.Fatal(err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
log.Fatal("Failed to append PEM.")
}
clientCert := make([]tls.Certificate, 0, 1)
certs, err := tls.LoadX509KeyPair("/path/mysqlClientCert", "/path/mysqlClientKey")
if err != nil {
log.Fatal(err)
}
clientCert = append(clientCert, certs)
mysql.RegisterTLSConfig("custom", &tls.Config{
RootCAs: rootCertPool,
Certificates: clientCert,
})
}
// try to connect to mysql database.
cfg := mysql.Config{
User: username,
Passwd: password,
Addr: server, //IP:PORT
Net: "tcp",
DBName: database,
Loc: time.Local,
AllowNativePasswords: true,
Params: o,
}
if isTLS == true {
cfg.TLSConfig = "custom"
}
str := cfg.FormatDSN()
db, err := gorm.Open("mysql", str)