connect to DB
This commit is contained in:
@ -6,20 +6,36 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
_ "github.com/jackc/pgconn"
|
||||
_ "github.com/jackc/pgx/v4"
|
||||
_ "github.com/jackc/pgx/v4/stdlib"
|
||||
)
|
||||
|
||||
const webPort = "4000"
|
||||
|
||||
var counts int64
|
||||
|
||||
type Config struct {
|
||||
DB *sql.DB
|
||||
Models data.Models
|
||||
}
|
||||
|
||||
func main() {
|
||||
// TODO connect to DB
|
||||
// connect to DB
|
||||
conn := connectToDB()
|
||||
|
||||
if conn == nil {
|
||||
log.Panic("Can't connect to Postgres!")
|
||||
}
|
||||
|
||||
// set up config
|
||||
app := Config{}
|
||||
app := Config{
|
||||
DB: conn,
|
||||
Models: data.New(conn),
|
||||
}
|
||||
|
||||
log.Printf("Starting authentication service on port %s\n", webPort)
|
||||
|
||||
@ -34,3 +50,39 @@ func main() {
|
||||
log.Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func openDB(dsn string) (*sql.DB, error) {
|
||||
db, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func connectToDB() *sql.DB {
|
||||
dsn := os.Getenv("DSN")
|
||||
|
||||
for {
|
||||
connection, err := openDB(dsn)
|
||||
if err != nil {
|
||||
log.Println("Postgres not yet ready ...")
|
||||
counts++
|
||||
} else {
|
||||
log.Println("Connected to Postgres!")
|
||||
return connection
|
||||
}
|
||||
|
||||
if counts > 10 {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Println("Backing off for two seconds...")
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user