fixes and improvements in broker and render
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
package goblocks
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -129,17 +132,13 @@ func (s *SSEBroker) HandleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
for {
|
||||
select {
|
||||
case message := <-client.Send:
|
||||
slog.Info("message", "message", message)
|
||||
var data string
|
||||
switch v := message.Data.(type) {
|
||||
case string:
|
||||
data = v
|
||||
case map[string]any, []any:
|
||||
jsonData, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
slog.Error("error marshaling message", "error", err)
|
||||
continue
|
||||
}
|
||||
data = string(jsonData)
|
||||
case template.HTML:
|
||||
data = string(v)
|
||||
default:
|
||||
jsonData, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
@@ -148,7 +147,14 @@ func (s *SSEBroker) HandleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
data = string(jsonData)
|
||||
}
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", message.Event, data)
|
||||
fmt.Fprintf(w, "event: %s\n", message.Event)
|
||||
|
||||
scanner := bufio.NewScanner(strings.NewReader(data))
|
||||
for scanner.Scan() {
|
||||
fmt.Fprintf(w, "data: %s\n", scanner.Text())
|
||||
}
|
||||
|
||||
fmt.Fprint(w, "\n")
|
||||
case <-client.Close:
|
||||
slog.Info("client closed", "client_id", clientID)
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user