-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_handler.go
60 lines (50 loc) · 1.28 KB
/
http_handler.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
package pqstream
import (
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/lib/pq"
)
type EventstreamHandler struct {
PostgreSQLConnectionString string
}
func (e EventstreamHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
topicsStr := req.URL.Query().Get("topics")
topics := strings.Split(topicsStr, ",")
upgrader := websocket.Upgrader{}
conn, err := upgrader.Upgrade(res, req, nil)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
reportProblem := func(ev pq.ListenerEventType, err error) {
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
}
listener := pq.NewListener(e.PostgreSQLConnectionString, time.Millisecond*1000, time.Second*10, reportProblem)
err = listener.Listen("eventstream")
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
subscription, err := NewSubscription(req.Context(), e.PostgreSQLConnectionString, topics...)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
defer subscription.Cancel()
for {
select {
case event := <-subscription.C:
err = conn.WriteJSON(event)
if err != nil {
log.Println("Write:", err)
break
}
}
}
}