-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_notify_tail.go
67 lines (57 loc) · 1.33 KB
/
pg_notify_tail.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
62
63
64
65
66
67
// Packakge main has the CLI entrypoint for pg-notify-tail
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jessedearing/pg-notify-tail/internal/config"
"github.com/jessedearing/pg-notify-tail/internal/pg"
)
var (
pgurl string
)
func main() {
cfg := config.Config{}
flag.StringVar(&cfg.PostgresURL, "pgurl", "", "Postgres URL in the form of 'postgres://user:password@host:port/db'")
flag.StringVar(&cfg.Channel, "channel", "", "The name of the channel to listen on")
flag.Parse()
err := cfg.Validate()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
if err != nil {
exitWithError(err)
return
}
conn, err := pgx.Connect(ctx, cfg.PostgresURL)
if err != nil {
exitWithError(err)
return
}
_, err = conn.Exec(ctx, fmt.Sprintf("listen %s", cfg.Channel))
if err != nil {
exitWithError(err)
return
}
var notiChan = make(chan pgconn.Notification)
var errChan = make(chan error)
go pg.NotifyOnChannel(ctx, conn, notiChan, errChan)
for {
select {
case n := <-notiChan:
fmt.Fprintln(os.Stdout, n.Payload)
case err = <-errChan:
cancel()
exitWithError(err)
case <-ctx.Done():
return
}
}
}
func exitWithError(err error) {
fmt.Fprintln(os.Stderr, "ERROR", err.Error())
os.Exit(1)
}