Get started with the Go driver

Because Astra Managed Clusters is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra databases.

This quickstart explains how to install a driver, connect it to your Astra database, and then send some CQL statements to the database.

To use the Apache Cassandra GoCQL driver (gocql) with Astra databases, use the gocql-astra package. This package includes GoCQL and additional support for connections to Astra. Specifically, the gocql-astra package provides a custom gocql.HostDialer that facilitates GoCQL connections to Astra because GoCQL doesn’t directly support connections to Astra.

GoCQL and GoCQL Astra compatibility

This quickstart uses gocql-astra 1.x, which uses gocql 1.x.

gocql-astra 2.x and gocql 2.x aren’t compatible with Astra Managed Clusters databases due to a known issue with HostDialer in gocql 2.x.

Prepare the environment and database

  1. Install Go version 1.22 or later.

    For more information, see Supported Versions in the GoCQL documentation.

  2. Create a database.

  3. Download your database’s Secure Connect Bundle (SCB).

    For more information, including connections to multi-region databases, see The SCB and encrypted connections for drivers.

  4. Set the following environment variables:

Authentication methods for drivers

You use an application token and a Secure Connect Bundle (SCB) to connect a driver to an Astra database.

The application token authenticates the driver to the database, and the token’s role determines the actions that the driver is authorized to perform on the database. When you generate a token, the token details include a clientId, secret, and token:

{
  "clientId": "CLIENT_ID",
  "secret": "CLIENT_SECRET",
  "token": "APPLICATION_TOKEN"
}
  • clientId and secret are legacy authentication methods that predate token.

  • token is a unified token that comprises everything you need for Astra token authentication.

Cassandra drivers use username and password authentication for Astra connections, typically through an authentication class or argument, such as PlainTextAuthProvider. To set the username and password for a Cassandra driver connection, you can use either the unified token or the legacy clientId and secret:

Unified token authentication (Recommended)

To authenticate with the unified application token, set the username to the literal string token, and set the password to your unified application token. For example:

("token", "APPLICATION_TOKEN")
Legacy clientId and secret authentication

For legacy applications and older driver versions that don’t use unified application tokens, you can use the clientId as the username and the secret as the password. For example:

("CLIENT_ID", "SECRET")

However, if you are using a legacy token created prior to the introduction of the unified token format, DataStax recommends rotating these tokens due to their age.

In addition to the application token, you must provide an SCB to set contact points and establish a secure connection to your database. For more information, see The SCB and encrypted connections for drivers.

The SCB and encrypted connections for drivers

In addition to an application token, you must provide an SCB to set contact points and provide certificates necessary to establish a secure mutual TLS (mTLS) connection to your database.

To establish an encrypted connection between your application and database, the driver uses the SSL certificates and trusted certificate authorities (CAs) in the SCB to verify the Astra server’s identity. Mechanically, when the driver receives the server’s SSL certificate during the SSL handshake, it checks that the certificate was signed by one of the registered CAs. If the certificate wasn’t signed by a registered CA, the driver checks that the signer was signed by one of the registered CAs. It continues through the signers until it finds one that is in the list of trusted CAs. If there are no matches, then identity verification fails and the driver connection isn’t established.

All Astra-compatible drivers have configuration file attributes, builder methods, or constructor parameters to use the SCB. In your driver configuration, you set the path to the SCB zip file, and then the driver automatically gets the required information and files from the SCB. When using an SCB, don’t set any options that are inferred from the SCB, such as contact points and SSL encryption settings. Additionally, don’t extract the SCB zip file; it must be provided to the driver as an unextracted archive.

For multi-region databases, you need the region-specific SCB for each region that your application will connect to.

To connect to one region of a multi-region database, download the SCB for a region that is geographically close to your application to reduce latency.

To connect to multiple regions or databases in the same application, download the SCB for each region or database. Then, in your application’s code, create one root driver instance (session or cluster) for each region or database, using custom logic to select the appropriate SCB for each instance. For more information, see Best practices: Session and cluster handling and Connection pools and initial contact points.

DataStax recommends that you use a driver version that supports SCB authentication for simplified configuration and reduced chance of connection failures. However, if you must support a legacy application with an earlier driver, you can use cql-proxy, extract the SCB, and then manually provide the required certificates to the driver. Additionally, you must use the token’s clientId and secret for the username and password, respectively. For an example, see DataStax Ruby and PHP drivers (Maintenance).

Install gocql-astra

In the root of your Go project directory, add gocql-astra:

go get github.com/datastax/gocql-astra

gocql-astra includes the gocql package.

Connect to your database

gocql-astra provides support to connect gocql to Astra databases.

For more information about driver connections, see Best practices: Session and cluster handling, and Connection pools and initial contact points.

Connect with an application token only

Write a script to connect gocql to your database using the APPLICATION_TOKEN and DATABASE_ID environment variables.

The following example imports the necessary classes, sets up a session, authenticates with an application token, and runs a SELECT statement on the system.local table. You can replace the example SELECT statement with any CQL statement that you want to run against a keyspace and table in your database.

package main

import (
    "fmt"
    "log"
    "os"
    "time"

    gocqlastra "github.com/datastax/gocql-astra"
    "github.com/gocql/gocql"
)

func main() {

    var err error

    var cluster *gocql.ClusterConfig

    if len(os.Getenv("APPLICATION_TOKEN")) > 0 {

        if len(os.Getenv("DATABASE_ID")) == 0 {
            panic("database ID is required when using a token")
        }
    }

    cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 10*time.Second)

    if err != nil {
        log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
    }

    cluster.Timeout = 30 * time.Second
    start := time.Now()
    session, err := gocql.NewSession(*cluster)
    elapsed := time.Now().Sub(start)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

    fmt.Println("Making the query now")

    iter := session.Query("SELECT release_version FROM system.local").Iter()

    var version string

    for iter.Scan(&version) {
        fmt.Println(version)
    }

    if err = iter.Close(); err != nil {
        log.Printf("error running query: %v", err)
    }

    fmt.Printf("Connection process took %s
", elapsed)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

}

Enable SSL encryption with an SCB

To connect with SSL encryption, use the gocql-astra method that accepts an SCB path and application token:

  1. Set an environment variable for your database’s SCB zip file, such as ASTRA_DB_SECURE_BUNDLE_PATH. For more information, see Prepare the environment and database.

  2. Run a script such as the following to connect to your database. This code imports the necessary classes, sets up a session, and authenticates with an SCB.

    In the authentication credentials, the literal string token is required for successful authentication. For more information, see Token details.

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "time"
    
        gocqlastra "github.com/datastax/gocql-astra"
        "github.com/gocql/gocql"
    )
    
    func main() {
    
        var cluster *gocql.ClusterConfig
    
        cluster, err := gocqlastra.NewClusterFromBundle(os.Getenv("ASTRA_DB_SECURE_BUNDLE_PATH"),
            "token", os.Getenv("APPLICATION_TOKEN"), 30*time.Second)
    
        if err != nil {
            panic("unable to load the bundle")
        }
        cluster.Timeout = 30 * time.Second
    
        session, err := gocql.NewSession(*cluster)
    
        if err != nil || session == nil {
            log.Fatalf("unable to connect session: %v", err)
        } else {
            fmt.Println("Success!")
        }
    
    }

Run commands

With gocql-astra, your scripts can use gocql commands to perform operations on your database.

For example, the following sample script performs these operations:

  • Defines the Book object

  • Connects to the database with an application token

  • Create a books table

  • Inserts two rows into the table

  • Retries the inserted rows

  • Updates one row

  • Deletes one row

  • Deletes the table

main.go
package main

import (
    "fmt"
    "log"
    "os"
    "time"

    gocqlastra "github.com/datastax/gocql-astra"
    "github.com/gocql/gocql"
)

type Book struct {
    ID     gocql.UUID
    Title  string
    Author string
    Year   int
}

func main() {

    var err error

    var cluster *gocql.ClusterConfig

    if len(os.Getenv("APPLICATION_TOKEN")) > 0 {
        if len(os.Getenv("DATABASE_ID")) == 0 {
            panic("database ID is required when using a token")
        }
    }

    fmt.Println("Creating the cluster now")

    cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 20*time.Second)
    if err != nil {
        log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
    }
    cluster.Timeout = 30 * time.Second
    session, err := gocql.NewSession(*cluster)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

    defer session.Close()

    // Delete the table
    if err := session.Query(`DROP TABLE IF EXISTS library.books`).Exec(); err != nil {
        fmt.Println("Dropping table to clean for examples.")
    }

    // Create the table
    fmt.Println("Creating the table now")
    if err := session.Query(`CREATE TABLE library.books ( id uuid PRIMARY KEY, title text, author text, year int );`).Exec(); err != nil {
        log.Fatal(err)
    }
    // Create Rows
    newBook := Book{
        ID:     gocql.TimeUUID(),
        Title:  "Go Programming",
        Author: "John Doe",
        Year:   2023,
    }

    secondBook := Book{
        ID:     gocql.TimeUUID(),
        Title:  "Zen and the Art of Go",
        Author: "Jane Doe",
        Year:   2023,
    }

    fmt.Println("Adding the books now:")

    if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
        newBook.ID, newBook.Title, newBook.Author, newBook.Year).Exec(); err != nil {
        log.Fatal(err)
    }

    if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
        secondBook.ID, secondBook.Title, secondBook.Author, secondBook.Year).Exec(); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Querying the books now:")
    iter := session.Query(`SELECT id, title, author, year FROM library.books`).Iter()

    var books []Book
    var book Book
    for iter.Scan(&book.ID, &book.Title, &book.Author, &book.Year) {
        books = append(books, book)
    }

    if err := iter.Close(); err != nil {
        log.Fatal(err)
    }

    // Print all books
    for _, book := range books {
        fmt.Println("Book:", book)
    }

    // Update
    updatedBook := Book{
        ID:     newBook.ID,
        Title:  "Advanced Go Programming",
        Author: "John Doe",
        Year:   2024,
    }

    if err := session.Query(`UPDATE library.books SET title = ?, author = ?, year = ? WHERE id = ?`,
        updatedBook.Title, updatedBook.Author, updatedBook.Year, updatedBook.ID).Exec(); err != nil {
        log.Fatal(err)
    }

    // Delete
    if err := session.Query(`DELETE FROM library.books WHERE id = ?`, newBook.ID).Exec(); err != nil {
        log.Fatal(err)
    }

}

To run the sample script, do the following:

  1. In your Go project directory, create a main.go file.

  2. Copy the sample script to main.go, and then save the file.

    The sample script creates and deletes a table. If you run it as is, the books table won’t exist in your database after the script ends. Consider breaking the sample script into smaller scripts, or comment out the DELETE commands, if you want to preserve the books table for additional testing.

  3. Run main.go:

    go run main.go

Next, extend or modify this script to run other commands against your database or connect to other databases. For more information, see the GoCQL and GoCQL Astra documentation.

Reconnect the Go driver after a migration

If you migrate your data from one Cassandra database platform to another, you must update your client applications to connect to your new databases.

At minimum, you must update the driver connection strings. Additional changes might be required if you upgraded to a new major driver version or migrated to a database platform with a different feature set. For example, if you migrate to Astra, your drivers cannot create keyspaces because CQL for Astra doesn’t support CREATE KEYSPACE.

For information about updating driver connections after a migration, see the DataStax migration documentation on Connecting client applications to your new target database. Although the referenced documentation is in the context of zero downtime migration, the information applies to most Cassandra-to-Cassandra migrations where you need to update Cassandra driver connection strings.

If you plan to migrate from Astra to a self-managed Cassandra deployment (such as HCD), you must switch to gocql directly after the migration. gocql-astra is used exclusively for connections to Astra databases.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM