-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (51 loc) · 1.1 KB
/
main.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/stdlib"
)
var (
db = ""
duration = time.Minute * 15
sleep = time.Second * 1
)
func init() {
flag.StringVar(&db, "db", db, "PostgreSQL database URI to connect (required)")
flag.DurationVar(&duration, "duration", duration, "how long we should wait before returning an error")
flag.DurationVar(&sleep, "sleep", sleep, "how long we should wait before next try")
}
func main() {
flag.Parse()
if db == "" {
fmt.Printf("Error: db - is required option.\n\n")
flag.PrintDefaults()
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
log.Println("start to wait for the database...")
for {
select {
case <-ctx.Done():
log.Fatalf("waiting failed: %s", ctx.Err())
case <-time.After(sleep):
}
db, err := sql.Open("pgx", db)
if err != nil {
log.Println("can't connect to database...")
continue
}
err = db.Ping()
if err != nil {
log.Println("can't ping database...")
continue
}
log.Println("connected!")
break
}
}