-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
57 lines (45 loc) · 1.05 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
package main
import (
"context"
"log"
"os"
"time"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
const (
heartbeat = 25 * time.Second
pingTimeout = 1 * time.Second
)
func WaitForNotification(origCtx context.Context, conn *pgx.Conn) error {
ctx, cancel := context.WithTimeout(origCtx, heartbeat)
defer cancel()
n, err := conn.WaitForNotification(ctx)
if err == nil {
log.Printf("[%d] %s: %s\n", n.PID, n.Channel, n.Payload)
} else if pgconn.Timeout(err) {
ctx, cancel = context.WithTimeout(origCtx, pingTimeout)
defer cancel()
err = conn.Ping(ctx)
}
return err
}
func main() {
conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal("Connect error", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if _, err = conn.Exec(ctx, "LISTEN foo"); err != nil {
log.Println("LISTEN query error", err)
return
}
for {
err := WaitForNotification(ctx, conn)
if err != nil {
log.Println("WaitForNotification or Ping error", err)
return
}
}
}