-
Notifications
You must be signed in to change notification settings - Fork 806
/
main.go
73 lines (59 loc) · 1.53 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
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"bufio"
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
var pool *pgxpool.Pool
func main() {
var err error
pool, err = pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, "Unable to connect to database:", err)
os.Exit(1)
}
go listen()
fmt.Println(`Type a message and press enter.
This message should appear in any other chat instances connected to the same
database.
Type "exit" to quit.`)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
msg := scanner.Text()
if msg == "exit" {
os.Exit(0)
}
_, err = pool.Exec(context.Background(), "select pg_notify('chat', $1)", msg)
if err != nil {
fmt.Fprintln(os.Stderr, "Error sending notification:", err)
os.Exit(1)
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Error scanning from stdin:", err)
os.Exit(1)
}
}
func listen() {
conn, err := pool.Acquire(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, "Error acquiring connection:", err)
os.Exit(1)
}
defer conn.Release()
_, err = conn.Exec(context.Background(), "listen chat")
if err != nil {
fmt.Fprintln(os.Stderr, "Error listening to chat channel:", err)
os.Exit(1)
}
for {
notification, err := conn.Conn().WaitForNotification(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for notification:", err)
os.Exit(1)
}
fmt.Println("PID:", notification.PID, "Channel:", notification.Channel, "Payload:", notification.Payload)
}
}