2024-08-28 10:55:03 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"authentication/data"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2024-08-28 11:06:37 +00:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
_ "github.com/jackc/pgconn"
|
|
|
|
_ "github.com/jackc/pgx/v4"
|
|
|
|
_ "github.com/jackc/pgx/v4/stdlib"
|
2024-08-28 10:55:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const webPort = "4000"
|
|
|
|
|
2024-08-28 11:06:37 +00:00
|
|
|
var counts int64
|
|
|
|
|
2024-08-28 10:55:03 +00:00
|
|
|
type Config struct {
|
|
|
|
DB *sql.DB
|
|
|
|
Models data.Models
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2024-08-28 11:06:37 +00:00
|
|
|
// connect to DB
|
|
|
|
conn := connectToDB()
|
|
|
|
|
|
|
|
if conn == nil {
|
|
|
|
log.Panic("Can't connect to Postgres!")
|
|
|
|
}
|
2024-08-28 10:55:03 +00:00
|
|
|
|
|
|
|
// set up config
|
2024-08-28 11:06:37 +00:00
|
|
|
app := Config{
|
|
|
|
DB: conn,
|
|
|
|
Models: data.New(conn),
|
|
|
|
}
|
2024-08-28 10:55:03 +00:00
|
|
|
|
|
|
|
log.Printf("Starting authentication service on port %s\n", webPort)
|
|
|
|
|
|
|
|
// define http server
|
|
|
|
srv := &http.Server{
|
|
|
|
Addr: fmt.Sprintf(":%s", webPort),
|
|
|
|
Handler: app.routes(),
|
|
|
|
}
|
|
|
|
|
|
|
|
err := srv.ListenAndServe()
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
}
|
2024-08-28 11:06:37 +00:00
|
|
|
|
|
|
|
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 {
|
2024-08-28 12:23:32 +00:00
|
|
|
log.Println("Postgres not yet ready ...: ", err)
|
2024-08-28 11:06:37 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|