Created
March 5, 2021 15:12
-
-
Save dmlyons/286c075bd6d823c3e047494ce1c97073 to your computer and use it in GitHub Desktop.
An example of setting a connection timeout on pgx stdlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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