aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-04-10 15:38:52 +0100
committerMatthew Lemon <y@yulqen.org>2024-04-10 15:38:52 +0100
commit6d6cd2ed8f1d723031b21771eab056bf2ec0fc00 (patch)
tree20d1719c7401d4b5ffb12d8a3894032639a05560
parent50d6737b0c81869d77486fded1476f55917b940b (diff)
Adds some database pool configuration and flags
-rw-r--r--cmd/dbasik-api/main.go20
1 files changed, 19 insertions, 1 deletions
diff --git a/cmd/dbasik-api/main.go b/cmd/dbasik-api/main.go
index e296551..e86f91c 100644
--- a/cmd/dbasik-api/main.go
+++ b/cmd/dbasik-api/main.go
@@ -43,7 +43,10 @@ type config struct {
port int
env string
db struct {
- dsn string
+ dsn string
+ maxOpenConns int
+ maxIdleConns int
+ maxIdleTime string
}
}
@@ -67,6 +70,12 @@ func main() {
flag.IntVar(&cfg.port, "port", 5000, "API server port")
flag.StringVar(&cfg.env, "env", "development", "Environment (development|staging|production)")
flag.StringVar(&cfg.db.dsn, "db-dsn", os.Getenv("DBASIK_DB_DSN"), "PostgreSQL DSN")
+
+ //Read connection pool settings (explained in Configuring the pool in the book)
+ flag.IntVar(&cfg.db.maxOpenConns, "db-max-open-conns", 25, "PostgreSQL max open connections")
+ flag.IntVar(&cfg.db.maxIdleConns, "db-max-idel-conns", 25, "PostgreSQL max idle connections")
+ flag.StringVar(&cfg.db.maxIdleTime, "db-max-idel-conns", "15m", "PostgreSQL max connection idle time")
+
flag.Parse()
// Initialize a new structured logger which writes to stdout
@@ -112,6 +121,15 @@ func openDB(cfg config) (*sql.DB, error) {
return nil, err
}
+ // set up pool config
+ db.SetMaxOpenConns(cfg.db.maxOpenConns)
+ db.SetMaxIdleConns(cfg.db.maxIdleConns)
+ duration, err := time.ParseDuration(cfg.db.maxIdleTime)
+ if err != nil {
+ return nil, err
+ }
+ db.SetConnMaxIdleTime(duration)
+
// create a context with a 5 second timeout
// if the database hasn't connected within this time, there is a problem
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)