Fix: sse changes

This commit is contained in:
Grail Finder
2025-05-10 09:01:51 +03:00
parent 2f4891473b
commit 416cc63ec0
6 changed files with 44 additions and 31 deletions

View File

@ -4,7 +4,6 @@ import (
"fmt"
"log/slog"
"net/http"
"strings"
"time"
)
@ -73,18 +72,21 @@ func (broker *Broker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
messageChan := make(NotifierChan)
broker.newClients <- messageChan
defer func() { broker.closingClients <- messageChan }()
ctx := r.Context()
for {
event := <-messageChan
// // Proper SSE formatting
// fmt.Fprintf(w, "event: %s\n", event.EventName) // Event name line
// fmt.Fprintf(w, "data: %s\n\n", event.Payload) // Data line + empty line
// Alternative for multi-line data:
fmt.Fprintf(w, "event: %s\n", event.EventName)
for _, line := range strings.Split(event.Payload, "\n") {
fmt.Fprintf(w, "data: %s\n", line)
select {
case <-ctx.Done():
// Client disconnected
return
case event := <-messageChan:
_, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event.EventName, event.Payload)
if err != nil {
fmt.Println(err)
// Client disconnected
return
}
w.(http.Flusher).Flush()
}
fmt.Fprintf(w, "\n")
w.(http.Flusher).Flush()
}
}