From 0fd673cd191d95b48eafd5d659d706d77d583bea Mon Sep 17 00:00:00 2001 From: Fanir Date: Tue, 25 Jan 2022 23:58:41 +0100 Subject: [PATCH] added retries in database.Open() --- cmd/feedizer/database/database.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/cmd/feedizer/database/database.go b/cmd/feedizer/database/database.go index 47bd837..e193c9f 100644 --- a/cmd/feedizer/database/database.go +++ b/cmd/feedizer/database/database.go @@ -3,6 +3,8 @@ package database import ( "database/sql" "fmt" + "log" + "time" "git.zom.bi/fanir/feedizer/cmd/feedizer/config" "git.zom.bi/fanir/feedizer/models/migrations" @@ -22,7 +24,25 @@ func Open(c config.DatabaseConfig) (*sql.DB, error) { dsn = fmt.Sprintf("postgres://%s:%s@%s:%d/%s?%s", c.Username, c.Password, c.Host, c.Port, c.Database, c.Options) LogName = fmt.Sprintf("%s:%d/%s", c.Host, c.Port, c.Database) } - return sql.Open("postgres", dsn) + + log.Printf("database: connecting...") + db, err := sql.Open("postgres", dsn) + if err != nil { + return nil, err + } + + err = db.Ping() + for i := 1; err != nil && i < 10; i++ { + log.Printf("database: connection failed, retrying in %d seconds...", i) + time.Sleep(time.Duration(i) * time.Second) + err = db.Ping() + } + + if err == nil { + log.Println("database: connection successful") + } + + return db, err } func Migrate(db *sql.DB) error {