云数据库 GAUSSDB NOSQL-通过Go语言连接实例:使用CCM私有证书连接实例的示例代码

时间:2023-11-10 12:13:26

使用CCM私有证书连接实例的示例代码

package main

import (
    "fmt"
    "io/ioutil"
    "crypto/tls"
    "crypto/x509"
    _ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod
    client "github.com/influxdata/influxdb1-client/v2"
)

func main(){
    pool := x509.NewCertPool()
    caCertPath := "/data/CA/agent/ca.crt"
    caCrt, err := ioutil.ReadFile(caCertPath)
    if err != nil {
        fmt.Println("ReadFile err:", err)
        return
    }
    pool.AppendCertsFromPEM(caCrt) // 此处是将ca.crt证书内嵌到程序中,也可以使用sudo cp {client}/ca.crt /etc/ssl/certs命令将证书添加到本机上。
    c, err := client.NewHTTPClient(client.HTTPConfig{
        Addr: "https://ip:port",
        Username: "******",
        Password: "******",
        TLSConfig: &tls.Config{
            RootCAs: pool,
            InsecureSkipVerify: false,  // false表示需要校验服务端的证书。
        },
    })
    if err != nil {
        fmt.Println("Error creating InfluxDB Client: ", err.Error())
    }
    q := client.NewQuery("select * from cpu","database","ns")
    if response, err := c.Query(q); err == nil && response.Error() == nil {
        fmt.Println("the result is: ",response.Results)
    }
}
support.huaweicloud.com/productdesc-nosql/nosql_09_0073.html