This section describes how to access a CSS cluster using Go.
Connect to a non-security mode cluster. The sample code is as follows:
1234567891011121314151617package mainimport ("github.com/elastic/go-elasticsearch/v7""log")func main() {cfg := elasticsearch.Config{Addresses: []string{"http://HOST:9200/",},}es, _ := elasticsearch.NewClient(cfg)log.Println(es.Info())}
In the information above, HOST indicates the internal IP address of a cluster node.
12345678910111213141516171819package mainimport ("github.com/elastic/go-elasticsearch/v7""log")func main() {cfg := elasticsearch.Config{Addresses: []string{"http://HOST:9200/",},Username: "USERNAME",Password: "PASSWORD",}es, _ := elasticsearch.NewClient(cfg)log.Println(es.Info())}
1234567891011121314151617181920212223242526package mainimport ("crypto/tls""github.com/elastic/go-elasticsearch/v7""log""net/http")func main() {cfg := elasticsearch.Config{Addresses: []string{"https://HOST:9200/",},Username: "USERNAME",Password: "PASSWORD",Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true,},},}es, _ := elasticsearch.NewClient(cfg)log.Println(es.Info())}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package mainimport ("crypto/tls""crypto/x509""flag""github.com/elastic/go-elasticsearch/v7""io/ioutil""log""net""net/http""time")func main() {insecure := flag.Bool("insecure-ssl", false, "Accept/Ignore all server SSL certificates")flag.Parse()// Get the SystemCertPool, continue with an empty pool on errorrootCAs, _ := x509.SystemCertPool()if rootCAs == nil {rootCAs = x509.NewCertPool()}// Read in the cert filecerts, err := ioutil.ReadFile("/tmp/CloudSearchService.cer")if err != nil {log.Fatalf("Failed to append %q to RootCAs: %v", "xxx", err)}// Append our cert to the system poolif ok := rootCAs.AppendCertsFromPEM(certs); !ok {log.Println("No certs appended, using system certs only")}config := elasticsearch.Config{Addresses: []string{"https://HOST:9200/",},Username: "USERNAME",Password: "PASSWORD",Transport: &http.Transport{MaxIdleConnsPerHost: 10,ResponseHeaderTimeout: time.Second,DialContext: (&net.Dialer{Timeout: 30 * time.Second,KeepAlive: 30 * time.Second,}).DialContext,TLSClientConfig: &tls.Config{InsecureSkipVerify: *insecure,RootCAs: rootCAs,},},}es, _ := elasticsearch.NewClient(config)log.Println(elasticsearch.Version)log.Println(es.Info())}
Parameter | Description |
|---|---|
HOST | IP address for accessing the Elasticsearch cluster. If there are multiple IP addresses, separate them with commas (,). |
USERNAME | Username for accessing the cluster. |
PASSWORD | Password of the user. |
Write the code above to the EsTest.gc file based on the cluster type and save the file to an independent directory. Run the following command in that directory to run the code:
go env -w GO111MODULE=ongo env -w GOPROXY=https://goproxy.io,directgo env -w GONOSUMDB=*go mod init testgo mod tidygo run EsTest.go