Connecting to ClickHouse with Go
In this example we will show how you can use the official Go driver for ClickHouse to connect to your cluster. Before you begin, it is imperative to review the general steps and considerations for connecting to a ClickHouse cluster as outlined in Connecting to a ClickHouse Cluster.
1. First, make sure you have go installed. Run the below command to confirm.
1 |
go version |
If not installed, download the latest go using curl and then install the package or msi file:
1 |
MacOS: curl -o go1.23.4.darwin-amd64.pkg https://golang.org/dl/go1.23.4.darwin-amd64.pkg |
1 |
Windows: curl -o go1.23.4.darwin-amd64.pkg https://golang.org/dl/go1.23.4.darwin-amd64.msi |
To find more about the installation process please check out: https://go.dev/doc/install
2. Initialize a module by running the following in command:
1 2 3 |
mkdir clickhouse-golang-example cd clickhouse-golang-example go mod init clickhouse-golang-example |
3. Copy the below code into the clickhouse-golang-example directory as main.go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
package main import ( "context" "crypto/tls" "fmt" "log" "github.com/ClickHouse/clickhouse-go/v2" "github.com/ClickHouse/clickhouse-go/v2/lib/driver" ) func main() { conn, err := connect() if err != nil { panic((err)) } ctx := context.Background() rows, err := conn.Query(ctx, "SHOW CLUSTERS") if err != nil { log.Fatal(err) } for rows.Next() { var ( cluster string ) if err := rows.Scan( &cluster, ); err != nil { log.Fatal(err) } log.Printf("cluster: %s", cluster) } } func connect() (driver.Conn, error) { var ( ctx = context.Background() conn, err = clickhouse.Open(&clickhouse.Options{ Addr: []string{"ip-34-211-57-139.aa02943daeb84be386e9b85c58f113a7.cu.dev.instaclustr.com:9440", "ip-44-228-126-5.aa02943daeb84be386e9b85c58f113a7.cu.dev.instaclustr.com:9440", "ip-52-38-245-50.aa02943daeb84be386e9b85c58f113a7.cu.dev.instaclustr.com:9440"}, Auth: clickhouse.Auth{ Database: "default", Username: "icclickhouse", Password: "password-for-icclickhouse", }, TLS: &tls.Config{ }, }) ) if err != nil { return nil, err } if err := conn.Ping(ctx); err != nil { if exception, ok := err.(*clickhouse.Exception); ok { fmt.Printf("Exception [%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace) } return nil, err } return conn, nil } |
4. Next, run go mod tidy in command:
1 |
go mod tidy |
5. Finally, run the example:
1 |
go run . |
To learn more about ClickHouse Go see https://github.com/ClickHouse/clickhouse-docs/blob/main/docs/integrations/language-clients/go/index.md