48 lines
No EOL
1.2 KiB
Go
48 lines
No EOL
1.2 KiB
Go
package sse
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"sync"
|
|
)
|
|
|
|
var (
|
|
clients = make(map[string]map[chan string]bool) // checklist uuid → set of client channels
|
|
clientsMutex sync.Mutex
|
|
)
|
|
|
|
// RegisterClient registers a new SSE client
|
|
func RegisterClient(uuid string, ch chan string) {
|
|
clientsMutex.Lock()
|
|
if clients[uuid] == nil {
|
|
clients[uuid] = make(map[chan string]bool)
|
|
}
|
|
clients[uuid][ch] = true
|
|
clientsMutex.Unlock()
|
|
}
|
|
|
|
// UnregisterClient removes an SSE client
|
|
func UnregisterClient(uuid string, ch chan string) {
|
|
clientsMutex.Lock()
|
|
delete(clients[uuid], ch)
|
|
clientsMutex.Unlock()
|
|
}
|
|
|
|
// Broadcast sends a message to all SSE clients for a checklist
|
|
func Broadcast(uuid string, msg interface{}) {
|
|
js, _ := json.Marshal(msg)
|
|
log.Printf("Broadcasting to %s: %s", uuid, string(js))
|
|
clientsMutex.Lock()
|
|
clientCount := len(clients[uuid])
|
|
log.Printf("Number of SSE clients for %s: %d", uuid, clientCount)
|
|
for ch := range clients[uuid] {
|
|
select {
|
|
case ch <- string(js):
|
|
log.Printf("Message sent to client")
|
|
default:
|
|
log.Printf("Channel full, skipping message")
|
|
// skip if channel is full (consider logging in prod!)
|
|
}
|
|
}
|
|
clientsMutex.Unlock()
|
|
} |