Connect with Go
Connect a Go application to a Managed PostgreSQL service with the pgx driver, with TLS certificate verification and credentials read from the environment.
Prerequisites
You need:
- A running Managed PostgreSQL service.
- The Exoscale CLI, configured with your API credentials.
- Go 1.25 or later, required by the current
pgxv5 release. - Your client IP address in the service IP filter. See Restrict Connections to a Service.
The service accepts TLS connections only. The SSL modes, and how to retrieve the connection URI and the CA certificate, are explained in Connect with psql.
Create a module and install the driver:
go mod init example.com/pgsample
go get github.com/jackc/pgx/v5Retrieve the Connection URI and the CA Certificate
export PG_URI="$(exo dbaas show SERVICE_NAME -z ZONE --uri)"
exo dbaas ca-certificate -z ZONE > ca.pem
export PGSSLROOTCERT="$PWD/ca.pem"Parameters:
SERVICE_NAME: name of your Managed PostgreSQL service, for examplemy-postgresql.ZONE: Exoscale zone the service runs in, for examplech-gva-2.
PG_URI contains the avnadmin password. Keep it out of logs.
Connect
The URI returned by the CLI ends with ?sslmode=require. The sample rewrites the query string to
sslmode=verify-full and points the driver at the CA certificate. Save it as main.go:
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"time"
"github.com/jackc/pgx/v5"
)
// connString takes the service URI and upgrades it to full TLS verification.
func connString() (string, error) {
raw := os.Getenv("PG_URI")
if raw == "" {
return "", fmt.Errorf("PG_URI is not set")
}
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("parsing PG_URI: %w", err)
}
ca := os.Getenv("PGSSLROOTCERT")
if ca == "" {
return "", fmt.Errorf("PGSSLROOTCERT is not set")
}
q := u.Query()
q.Set("sslmode", "verify-full")
q.Set("sslrootcert", ca)
q.Set("application_name", "exoscale-go-sample")
u.RawQuery = q.Encode()
return u.String(), nil
}
func main() {
cs, err := connString()
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn, err := pgx.Connect(ctx, cs)
if err != nil {
log.Fatalf("connect: %v", err)
}
defer conn.Close(context.Background())
var version, database, user string
err = conn.QueryRow(ctx, "SELECT version(), current_database(), current_user").
Scan(&version, &database, &user)
if err != nil {
log.Fatalf("query: %v", err)
}
fmt.Printf("server: %s\n", version)
fmt.Printf("database: %s\n", database)
fmt.Printf("user: %s\n", user)
var tlsVersion, cipher string
err = conn.QueryRow(ctx,
"SELECT version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()").
Scan(&tlsVersion, &cipher)
if err != nil {
log.Fatalf("tls query: %v", err)
}
fmt.Printf("tls: %s %s\n", tlsVersion, cipher)
}Run it:
go run main.goThe last line shows the TLS version and cipher of the session, for example
tls: TLSv1.3 TLS_AES_256_GCM_SHA384.
If PGSSLROOTCERT points to the wrong certificate, the connection fails with
tls: failed to verify certificate: x509: certificate signed by unknown authority.
Build the query string with url.Values and Encode(), as the sample does. A query string
that separates parameters with ;, as in sslmode=verify-full;sslrootcert=ca.pem, is rejected
by pgx with cannot parse ... failed to parse as URL.
Use an absolute path for sslrootcert: a relative path is resolved from the working directory
of the process, which differs between go run and a deployed binary.
Use a Connection Pool
For a server application, use pgxpool instead of a single connection. It keeps a bounded set of
connections open, so requests do not pay for a new TLS handshake. Add the package to the module:
go get github.com/jackc/pgx/v5/pgxpoolThen replace the main function of main.go with the following, and adjust the imports to
context, fmt, log, net/url, os, time and github.com/jackc/pgx/v5/pgxpool.
connString() is the function defined above:
func main() {
cs, err := connString()
if err != nil {
log.Fatal(err)
}
cfg, err := pgxpool.ParseConfig(cs)
if err != nil {
log.Fatal(err)
}
cfg.MaxConns = 10
cfg.MinConns = 1
pool, err := pgxpool.NewWithConfig(context.Background(), cfg)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
var now time.Time
if err := pool.QueryRow(context.Background(), "SELECT now()").Scan(&now); err != nil {
log.Fatal(err)
}
fmt.Println(now)
}Read the server limit with SHOW max_connections; and keep the sum of MaxConns across all
your application instances below it. To share a small number of server connections between many
application instances, use a server-side pool: see
Manage Connection Pools.
Use database/sql
pgx provides an adapter for the standard database/sql interface. The same connection string
applies:
import (
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib"
)
db, err := sql.Open("pgx", cs)The older github.com/lib/pq driver, registered as postgres in database/sql, accepts the
same connection string, including sslmode=verify-full and sslrootcert.