aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/api/sse.go
blob: 7c2332c011649244fdceb030ecae931324e34d53 (plain)
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
package api

import (
	"fmt"
	"log"
	"net/http"

	"yaum/internal/sse"
)

type StreamHandler struct {
	broadcaster *sse.Broadcaster
}

func NewStreamHandler(b *sse.Broadcaster) *StreamHandler {
	return &StreamHandler{broadcaster: b}
}

func (sh *StreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming not supported", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("X-Accel-Buffering", "no")

	ch := sh.broadcaster.Subscribe()
	defer sh.broadcaster.Unsubscribe(ch)

	_, err := fmt.Fprintf(w, "event: connected\ndata: {}\n\n")
	if err != nil {
		return
	}
	flusher.Flush()

	ctx := r.Context()
	for {
		select {
		case data, ok := <-ch:
			if !ok {
				return
			}
			_, err := fmt.Fprintf(w, "event: heartbeat\ndata: %s\n\n", data)
			if err != nil {
				log.Printf("[sse] cliente desconectado: %v", err)
				return
			}
			flusher.Flush()
		case <-ctx.Done():
			return
		}
	}
}