-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
61 lines (53 loc) · 1.12 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
57
58
59
60
61
package main
import (
"context"
"fmt"
"net"
"os"
"sync"
"time"
"github.com/jackc/pgx/v4/pgxpool"
)
func WaitForPostgres(service string, timeOut time.Duration) error {
var pgChan = make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
go func(s string) {
defer wg.Done()
for {
_, err := net.Dial("tcp", service)
if err == nil {
return
}
time.Sleep(1 * time.Second)
}
}(service)
wg.Wait()
close(pgChan)
}()
select {
case <-pgChan:
return nil
case <-time.After(timeOut):
return fmt.Errorf("postgres isn't ready in %s", timeOut)
}
}
func main() {
if err := WaitForPostgres("db:5432", 30 * time.Second); err != nil {
fmt.Println(err)
os.Exit(1)
}
dbpool, err := pgxpool.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
}
defer dbpool.Close()
var greeting string
err = dbpool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
if err != nil {
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
os.Exit(1)
}
fmt.Println(greeting)
}