Skip to content

Commit

Permalink
Merge pull request #46 from TheWisePigeon/44-retry-system-when-connec…
Browse files Browse the repository at this point in the history
…ting-to-databases

retry 5 seconds later if failed to connect to database
  • Loading branch information
joseph0x45 authored Jan 6, 2024
2 parents 8576ec5 + faccc24 commit 2347dd4
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions internal/database/postgres.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
package database

import (
"fmt"
"os"
"time"

"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"os"
)

func connect() (db *sqlx.DB, err error) {
db, err = sqlx.Connect("postgres", os.Getenv("PG_URL"))
return
}

func NewPostgresPool() *sqlx.DB {
db, err := sqlx.Connect("postgres", os.Getenv("PG_URL"))
var db *sqlx.DB
db, err := connect()
if err != nil {
panic(err)
fmt.Println("Failed to connect to database server. Retrying in 5 seconds")
time.Sleep(time.Second * 5)
db, err = connect()
if err != nil {
fmt.Println("Failed to connect to database")
panic(err)
}
}
db.SetConnMaxLifetime(0)
db.SetMaxIdleConns(50)
Expand Down

0 comments on commit 2347dd4

Please sign in to comment.