How to Use Connection Pooling with database/sql

Configure connection pooling in Go by using sql.Open and setting MaxOpenConns, MaxIdleConns, and ConnMaxLifetime on the DB object.

Use the database/sql package's Open function with a DSN that supports connection pooling, then configure the pool limits on the returned *sql.DB object.

db, err := sql.Open("postgres", "user=postgres dbname=mydb sslmode=disable")
if err != nil {
    log.Fatal(err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)

The sql.Open call returns a *sql.DB that manages a pool of connections; it does not open a connection immediately. Set SetMaxOpenConns to limit total connections, SetMaxIdleConns to keep a minimum number ready, and SetConnMaxLifetime to close old connections automatically.