Fix: sse changes
This commit is contained in:
@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user