donglugou6652
donglugou6652
2018-10-24 06:07

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

已采纳

Can't seem to find any resource on creating a SSL connection to mysql using gorm. I am creating a non-ssl connection like this:

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)

Passing 'ssl-ca' option in Param options with path to 'pem' file does not seem to work. Any heads up on this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushu5451 doushu5451 2年前

    This is a fragment of my working code :

    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)
    
    点赞 评论 复制链接分享