连接到 mysql/mariadb 与 ssl 和 certs in go

有很多例子说明如何在只需要用户名和密码时使用go/golang连接到mariadb /mysql数据库。但是我还没有找到一个简单的例子,其中客户端需要证书(TLS / SSL)来连接。


这适用于香草连接


package main


import (

    "database/sql"

    "fmt"

    "log"


    _ "github.com/go-sql-driver/mysql"


// Test that db is usable

// prints current date & time to stdout

func queryDB(db *sql.DB) {

    // Query the database

    var result string

    err := db.QueryRow("SELECT NOW()").Scan(&result)

    if err != nil {

        log.Fatal(err)

    }

    fmt.Println(result)

}


func main() {

    // generate connection string

    cs := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", "username", "password", "dbHost", "dbPort", "database")

    db, err := sql.Open("mysql", cs)

    if err != nil {

        log.Printf("Error %s when opening DB\n", err)

        log.Printf("%s", cs)

        return

    }

    defer db.Close()

    e := db.Ping()

    fmt.Println(cs, e)

    queryDB(db)

}

但是,如果客户端需要证书进行连接,我应该将该信息放在哪里?


在我看来,这将是这些行:my.cnf


[mysql]

## MySQL Client Configuration ##

ssl-ca=cert/ca-cert.pem

ssl-cert=cert/client-cert.pem

ssl-key=cert/client-key.pem


幕布斯7119047
浏览 103回答 1
1回答

www说

为了能够使用证书进行身份验证,您必须创建一个,然后执行一个并添加到连接字符串中。tls.Configmysql.RegisterTLSConfig("custom", &tlsConf)"?tsl=custom"从何而来tls"crypto/tls"mysql"github.com/go-sql-driver/mysql"一个工作示例:package mainimport (    "crypto/tls"    "crypto/x509"    "database/sql"    "fmt"    "io/ioutil"    "log"    "github.com/go-sql-driver/mysql"    _ "github.com/go-sql-driver/mysql")// path to cert-files hard coded// Most of this is copy pasted from the internet// and used without much reflectionfunc createTLSConf() tls.Config {    rootCertPool := x509.NewCertPool()    pem, err := ioutil.ReadFile("cert/ca-cert.pem")    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("cert/client-cert.pem", "cert/client-key.pem")    if err != nil {        log.Fatal(err)    }    clientCert = append(clientCert, certs)    return tls.Config{        RootCAs:            rootCertPool,        Certificates:       clientCert,        InsecureSkipVerify: true, // needed for self signed certs    }}// Test that db is usable// prints version to stdoutfunc queryDB(db *sql.DB) {    // Query the database    var result string    err := db.QueryRow("SELECT NOW()").Scan(&result)    if err != nil {        log.Fatal(err)    }    fmt.Println(result)}func main() {    // When I realized that the tls/ssl/cert thing was handled separately    // it became easier, the following two lines are the important bit    tlsConf := createTLSConf()      err := mysql.RegisterTLSConfig("custom", &tlsConf)    if err != nil {        log.Printf("Error %s when RegisterTLSConfig\n", err)        return    }    // connection string (dataSourceName) is slightly different    dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?tls=custom", "username", "password", "dbHost", "dbPort", "database")    db1, err := sql.Open("mysql", dsn)    if err != nil {        log.Printf("Error %s when opening DB\n", err)        log.Printf("%s", dsn)        return    }    defer db1.Close()    e := db1.Ping()    fmt.Println(dsn, e)    queryDB(db1)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go