Skip to content

Instantly share code, notes, and snippets.

@mpenick
Created March 10, 2022 15:01
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 mpenick/efa054a61e721fc5c6beb13543b888f6 to your computer and use it in GitHub Desktop.
Save mpenick/efa054a61e721fc5c6beb13543b888f6 to your computer and use it in GitHub Desktop.
func NewClusterFromBundle(bundlePath string) (*gocql.ClusterConfig, error) {
reader, err := zip.OpenReader(bundlePath)
if err != nil {
return nil, err
}
defer reader.Close()
contents := make(map[string][]byte)
for _, file := range reader.File {
switch file.Name {
case "config.json", "cert", "key", "ca.crt":
bytes, err := loadBytes(file)
if err != nil {
return nil, err
}
contents[file.Name] = bytes
}
}
config := struct {
Host string `json:"host"`
Port int `json:"cql_port"`
Keyspace string `json:"keyspace"`
}{}
err = json.Unmarshal(contents["config.json"], &config)
if err != nil {
return nil, err
}
cert, err := tls.X509KeyPair(contents["cert"], contents["key"])
if err != nil {
return nil, err
}
caCerts := x509.NewCertPool()
if ok := caCerts.AppendCertsFromPEM(contents["ca.crt"]); !ok {
return nil, fmt.Errorf("unable to load CA certificate")
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCerts,
}
hosts, _ := lookupHost(config.Host, strconv.Itoa(config.Port))
cluster := gocql.NewCluster(hosts...)
cluster.HostFilter = ContactPointHostFilter(hosts)
cluster.Port = config.Port
cluster.Keyspace = config.Keyspace
cluster.SslOpts = &gocql.SslOptions{
Config: &tlsConfig,
}
return cluster, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment