Skip to content

Instantly share code, notes, and snippets.

@phact
Last active October 9, 2020 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phact/ce28d0db650715af87701071b2e32f27 to your computer and use it in GitHub Desktop.
Save phact/ce28d0db650715af87701071b2e32f27 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
. "github.com/gocql/gocql"
"io/ioutil"
"log"
"net/http"
"path/filepath"
)
func main() {
TestConnectionToAstra()
}
func readCloudConfig(_caCertPool *x509.CertPool, certs []tls.Certificate, url string) (Metadata, interface{}) {
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: certs,
RootCAs: _caCertPool,
},
},
}
resp, err := client.Get(url)
body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)
res := Metadata{}
json.Unmarshal([]byte(bodyString), &res)
return res, err
}
type ContactInfo struct {
LocalDc string `json:"local_dc"`
ContactInfoType string `json:"type"`
ContactPoints []string `json:"contact_points"`
SniProxyAddress string `json:"sni_proxy_address"`
}
type Metadata struct {
Version int
Region string
ContactInfo ContactInfo `json:"contact_info"`
}
func TestConnectionToAstra(){
var _cqlshrc_host = "b787504c-2e50-4227-954f-a169e68cf3ba-us-east1.db.astra.datastax.com"
var _cqlshrc_port = "31473"
var _metadata_port = "32312"
var _username = "datastax"
var _password = "datastax"
var _query = "SELECT host_id FROM system.peers"
cluster := NewCluster(_cqlshrc_host)
cluster.Authenticator = PasswordAuthenticator{
Username: _username,
Password: _password,
}
_certPath, _ := filepath.Abs("/home/tato/Downloads/myc10/cert")
_keyPath, _ := filepath.Abs("/home/tato/Downloads/myc10/key")
_caPath, _ := filepath.Abs("/home/tato/Downloads/myc10/ca.crt")
_cert, _ := tls.LoadX509KeyPair(_certPath, _keyPath)
_caCert, _ := ioutil.ReadFile(_caPath)
_caCertPool := x509.NewCertPool()
_caCertPool.AppendCertsFromPEM(_caCert)
_tlsConfig := &tls.Config{
Certificates: []tls.Certificate{_cert},
RootCAs: _caCertPool,
}
cluster.SslOpts = &SslOptions{
Config: _tlsConfig,
EnableHostVerification: false,
}
metadata, err := readCloudConfig(_caCertPool, []tls.Certificate{_cert}, "https://"+_cqlshrc_host+":"+_metadata_port+"/metadata")
if err != nil {
fmt.Printf("error with metadata svc %v", err)
}
fmt.Printf(metadata.ContactInfo.SniProxyAddress)
cluster.Hosts = []string{metadata.ContactInfo.SniProxyAddress}
cluster.Hosts = []string{_cqlshrc_host + ":" + _cqlshrc_port }
session, _ := cluster.CreateSession()
iter := session.Query(_query).Iter()
var hostId string
for iter.Scan(&hostId) {
fmt.Println(hostId)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment