如何使用gorm创建与MySQL的SSL连接?

时间:2018-10-24 06:07:49

标签: go go-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)

在Param选项中将'ssl-ca'选项传递到'pem'文件的路径似乎不起作用。有什么要注意的吗?

1 个答案:

答案 0 :(得分:1)

这是我的工作代码的一部分:

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)