ServeHTTP handles SSE connections at /api/events.
(w http.ResponseWriter, r *http.Request)
| 34 | |
| 35 | // ServeHTTP handles SSE connections at /api/events. |
| 36 | func (b *SSEBroker) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 37 | flusher, ok := w.(http.Flusher) |
| 38 | if !ok { |
| 39 | http.Error(w, "streaming unsupported", http.StatusInternalServerError) |
| 40 | return |
| 41 | } |
| 42 | |
| 43 | w.Header().Set("Content-Type", "text/event-stream") |
| 44 | w.Header().Set("Cache-Control", "no-cache") |
| 45 | w.Header().Set("Connection", "keep-alive") |
| 46 | |
| 47 | ch := make(chan struct{}, 1) |
| 48 | b.mu.Lock() |
| 49 | b.clients[ch] = struct{}{} |
| 50 | b.mu.Unlock() |
| 51 | |
| 52 | defer func() { |
| 53 | b.mu.Lock() |
| 54 | delete(b.clients, ch) |
| 55 | b.mu.Unlock() |
| 56 | }() |
| 57 | |
| 58 | // Send initial connected event |
| 59 | fmt.Fprintf(w, "event: connected\ndata: ok\n\n") |
| 60 | flusher.Flush() |
| 61 | |
| 62 | for { |
| 63 | select { |
| 64 | case <-ch: |
| 65 | fmt.Fprintf(w, "event: reload\ndata: changed\n\n") |
| 66 | flusher.Flush() |
| 67 | case <-r.Context().Done(): |
| 68 | return |
| 69 | } |
| 70 | } |
| 71 | } |