-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
35 lines (30 loc) · 814 Bytes
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main
import (
"fmt"
"time"
"github.com/caarlos0/env"
"github.com/jmoiron/sqlx"
)
type pgConfig struct {
Host string `env:"POSTGRES_HOST" envDefault:"localhost"`
DB string `env:"POSTGRES_DB" envDefault:"test"`
User string `env:"POSTGRES_USER" envDefault:"postgres"`
Pass string `env:"POSTGRES_PASSWORD" envDefault:"postgres"`
}
func connectDB() *sqlx.DB {
pgcfg := pgConfig{}
err := env.Parse(&pgcfg)
if err != nil {
panic(err)
}
for {
db, err := sqlx.Connect("postgres", fmt.Sprintf("host=%s dbname=%s user=%s password=%s sslmode=disable", pgcfg.Host, pgcfg.DB, pgcfg.User, pgcfg.Pass))
if err == nil {
fmt.Println("DB connected successfully!")
return db
} else {
fmt.Println("connecting to DB was not successful, trying again")
time.Sleep(time.Second * 3)
}
}
}