前提条件
使用非SSL方式连接实例的示例代码
package main
import (
"fmt"
_ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod
client "github.com/influxdata/influxdb1-client/v2"
)
func main(){
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://ip:port",
Username: "******",
Password: "******",
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
q := client.NewQuery("select * from cpu","db0","ns")
if response, err := c.Query(q); err == nil && response.Error() == nil {
fmt.Println("the result is: ",response.Results)
}
}
使用默认SSL证书连接实例的示例代码
package main
import (
"fmt"
_ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod
client "github.com/influxdata/influxdb1-client/v2"
)
func main(){
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "https://ip:port",
Username:"******",
Password:"******",
InsecureSkipVerify: true, // true表示不验证服务端的信息,可能存在被攻击的风险,建议设为false,具体请参见使用CCM私有证书连接实例的示例代码。
})
if err != nil {
fmt.Println("Error creating InfluxDB Client: ", err.Error())
}
q := client.NewQuery("select * from cpu","databases","ns")
if response, err := c.Query(q); err == nil && response.Error() == nil {
fmt.Println(response.Results)
}
}
使用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)
}
}