Skip to main content

Connect with Go

This example connects to PostgreSQL® service from Go, making use of the pg library.


These are the placeholders you will need to replace in the code sample:

POSTGRESQL_URIURL for PostgreSQL connection, from the service overview page


For this example you will need:

  • The Go pq library:

    go get
  • Download CA certificates from the service overview page, this example assumes it is in a local file called ca.pem.


Add the following to main.go and replace the placeholder with the PostgreSQL URI:

package main

import (

_ ""

func main() {

conn, _ := url.Parse(serviceURI)
conn.RawQuery = "sslmode=verify-ca;sslrootcert=ca.pem"

db, err := sql.Open("postgres", conn.String())

if err != nil {
defer db.Close()

rows, err := db.Query("SELECT version()")
if err != nil {

for rows.Next() {
var result string
err = rows.Scan(&result)
if err != nil {
fmt.Printf("Version: %s\n", result)

This code creates a PostgreSQL client and opens a connection to the database. Then runs a query checking the database version and prints the response


This example replaces the query string parameter to specify sslmode=verify-ca to make sure that the SSL certificate is verified, and adds the location of the cert.

To run the code:

go run main.go

If the script runs successfully, the outputs should be the PostgreSQL version running in your service like:

Version: PostgreSQL 13.3 on x86_64-pc-linux-gnu, compiled by gcc, a 68c5366192 p 6520304dc1, 64-bit