Skip to content

Instantly share code, notes, and snippets.

@dmlyons
Created March 5, 2021 15:12
Show Gist options
  • Save dmlyons/286c075bd6d823c3e047494ce1c97073 to your computer and use it in GitHub Desktop.
Save dmlyons/286c075bd6d823c3e047494ce1c97073 to your computer and use it in GitHub Desktop.
An example of setting a connection timeout on pgx stdlib
package main
import (
"database/sql"
"log"
"net"
"time"
"github.com/jackc/pgx"
"github.com/jackc/pgx/stdlib"
)
func main() {
timeOutDialer := net.Dialer{Timeout: 10 * time.Second}
driverConfig := stdlib.DriverConfig{
ConnConfig: pgx.ConnConfig{
Dial: timeOutDialer.Dial,
},
}
stdlib.RegisterDriverConfig(&driverConfig)
// try to open a connection to a non-existant database
db, err := sql.Open("pgx", driverConfig.ConnectionString("postgresql://postgres:postgres@192.168.192.192/test"))
if err != nil {
// it won't fail here, database/sql doesn't pull a connection until it needs it.
log.Fatal(err)
}
// here is where it actually tries to connect and will timeout
err = db.Ping()
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment