Skip to main content

Connect to Aiven for AlloyDB Omni with Go

Connect to an Aiven for AlloyDB Omni database from Go, making use of the pg library.

Prerequisites

Connect to a service

  1. 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.

    note

    To verify the SSL certificate, this code specifies sslmode as verify-ca and adds the location of the certificate.

  2. Run the code:

    go run main.go

Expect output like:

PostgreSQL 15.5 on x86_64-pc-linux-gnu, compiled by [...]