Skip to content

Commit 3b24404

Browse files
authored
Merge pull request #1 from syntasso/wait-for-postgres
Wait for postgres
2 parents 0dab099 + 4bd4b3c commit 3b24404

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

main.go

+33-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"log"
77
"os"
8+
"time"
89

910
_ "github.com/lib/pq"
1011

@@ -36,15 +37,21 @@ func main() {
3637
}
3738
defer db.Close()
3839

39-
if err := initDB(db); err != nil {
40-
log.Fatal(err)
41-
}
42-
4340
engine := html.New("./views", ".html")
4441
app := fiber.New(fiber.Config{
4542
Views: engine,
4643
})
4744

45+
//checked by kubernetes to see if the pod is ready to receive traffic
46+
app.Get("/healthz", func(c *fiber.Ctx) error {
47+
fmt.Println("healthcheck")
48+
err := db.Ping()
49+
if err != nil {
50+
c.SendString(err.Error())
51+
}
52+
return err
53+
})
54+
4855
app.Get("/", func(c *fiber.Ctx) error {
4956
return getTodos(c, db, version)
5057
})
@@ -61,6 +68,27 @@ func main() {
6168
app.Static("/", "./public")
6269
app.Use(logger.New())
6370

71+
//we need to keep re-trying until successful, but don't want to block
72+
//the api form starting, so we kick off a go-routine
73+
go func() {
74+
x := 0
75+
for {
76+
log.Println("Attempting to connect to DB")
77+
78+
if err := initDB(db); err == nil {
79+
break
80+
}
81+
82+
if x > 60 {
83+
log.Printf("Retried %d times, exiting\n", x)
84+
log.Fatal(err)
85+
}
86+
87+
log.Printf("Failed to connect to DB, retry attempt %d/60. Err: %v\n", x, err)
88+
time.Sleep(time.Second)
89+
x++
90+
}
91+
}()
6492
log.Println(app.Listen(fmt.Sprintf(":%v", port)))
6593
}
6694

@@ -78,6 +106,7 @@ func getTodos(c *fiber.Ctx, db *sql.DB, version string) error {
78106
rows.Scan(&res)
79107
todos = append(todos, res)
80108
}
109+
81110
return c.Render("index", fiber.Map{
82111
"Todos": todos,
83112
"Enterprise": os.Getenv("ENTERPRISE"),

0 commit comments

Comments
 (0)