-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_events.go
41 lines (35 loc) · 908 Bytes
/
handler_events.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
package main
import (
"fmt"
"net/http"
"htmxx/service"
)
func (h *application) EventsHandler(w http.ResponseWriter, r *http.Request) {
// handle SSE events
fmt.Println("Client Connected")
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
var channel = make(chan service.Event)
h.eventsService.AddChannel(&channel)
defer func() {
close(channel)
}()
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
}
for {
select {
case message := <-channel:
_, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", message.EventName, message.Data)
if err != nil {
fmt.Println(fmt.Printf("Error sending message: %v", err))
}
flusher.Flush()
case <-r.Context().Done():
h.eventsService.RemoveChannel(&channel)
return
}
}
}