66 "strconv"
77 "time"
88
9+ "github.com/create-go-app/net_http-go-template/pkg/utils"
910 "github.com/jmoiron/sqlx"
1011
1112 _ "github.com/jackc/pgx/v4/stdlib" // load pgx driver for PostgreSQL
@@ -18,21 +19,27 @@ func PostgreSQLConnection() (*sqlx.DB, error) {
1819 maxIdleConn , _ := strconv .Atoi (os .Getenv ("DB_MAX_IDLE_CONNECTIONS" ))
1920 maxLifetimeConn , _ := strconv .Atoi (os .Getenv ("DB_MAX_LIFETIME_CONNECTIONS" ))
2021
22+ // Build PostgreSQL connection URL.
23+ postgresConnURL , err := utils .ConnectionURLBuilder ("postgres" )
24+ if err != nil {
25+ return nil , err
26+ }
27+
2128 // Define database connection for PostgreSQL.
22- db , err := sqlx .Connect ("pgx" , os . Getenv ( "DB_SERVER_URL" ) )
29+ db , err := sqlx .Connect ("pgx" , postgresConnURL )
2330 if err != nil {
24- return nil , fmt .Errorf ("error, not connected to PostgreSQL database, %w" , err )
31+ return nil , fmt .Errorf ("error, not connected to database, %w" , err )
2532 }
2633
27- // Set database connection settings.
34+ // Set database connection settings:
2835 db .SetMaxOpenConns (maxConn ) // the default is 0 (unlimited)
2936 db .SetMaxIdleConns (maxIdleConn ) // defaultMaxIdleConns = 2
3037 db .SetConnMaxLifetime (time .Duration (maxLifetimeConn )) // 0, connections are reused forever
3138
3239 // Try to ping database.
3340 if err := db .Ping (); err != nil {
3441 defer db .Close () // close database connection
35- return nil , fmt .Errorf ("error, not sent ping to PostgreSQL database, %w" , err )
42+ return nil , fmt .Errorf ("error, not sent ping to database, %w" , err )
3643 }
3744
3845 return db , nil
0 commit comments