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
|
package handler
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.neonxp.dev/djson/internal/command"
)
func (h *handler) HandleEvents(r chi.Router) {
r.Route("/sse", func(r chi.Router) {
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
h.receiveEvents(w, r, func(ev *command.Mutation) {
message, _ := json.Marshal(ev.Data)
fmt.Fprintf(
w,
`event: %s\ndata: {"path":"%s","data":%s}\n\n`,
ev.Type.String(),
strings.Join(ev.Path, "/"),
message,
)
})
})
})
r.Route("/json", func(r chi.Router) {
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
h.receiveEvents(w, r, func(ev *command.Mutation) {
message, _ := json.Marshal(ev.Data)
fmt.Fprintf(
w,
`{"event":"%s","path":"%s","data":"%s"}\n`,
ev.Type.String(),
strings.Join(ev.Path, "/"),
message,
)
})
})
})
}
func (h *handler) receiveEvents(
w http.ResponseWriter,
r *http.Request,
render func(ev *command.Mutation),
) {
flusher := w.(http.Flusher)
w.Header().Set("Content-Type", "application/x-ndjson")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
rctx := chi.RouteContext(r.Context())
path := parsePath(rctx.RoutePath)
ch := make(chan command.Mutation)
reqID := middleware.GetReqID(r.Context())
h.events.Subscribe(path, reqID, ch)
defer h.events.Unsubscribe(path, reqID)
go func() {
for ev := range ch {
render(&ev)
flusher.Flush()
}
}()
<-r.Context().Done()
}
|