Connect with Go Early availability
Connect to an Aiven for AlloyDB Omni database from Go, making use of the pg
library.
Prerequisites
-
Aiven for AlloyDB Omni service running
-
Go
pq
library, which you can get by running:go get github.com/lib/pq
-
CA certificate (a file named
ca.pem
) downloaded from the service's Overview page
Connect to a service
-
Create a file named
main.go
with the following content:package main
import (
"database/sql"
"fmt"
"log"
"net/url"
_ "github.com/lib/pq"
)
func main() {
serviceURI := "POSTGRESQL_URI"
conn, _ := url.Parse(serviceURI)
conn.RawQuery = "sslmode=verify-ca;sslrootcert=ca.pem"
db, err := sql.Open("postgres", conn.String())
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("SELECT version()")
if err != nil {
panic(err)
}
for rows.Next() {
var result string
err = rows.Scan(&result)
if err != nil {
panic(err)
}
fmt.Printf("Version: %s\n", result)
}
}Replace
SERVICE_URI
with the service URI available on the Overview page in the Aiven Console.This code opens a connection to the database, runs a query checking the database version, and prints the response.
noteTo verify the SSL certificate, this code specifies
sslmode
asverify-ca
and adds the location of the certificate. -
Run the code:
go run main.go
Expect output like:
PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]