Add SSE broadcaster
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package web
|
||||
|
||||
import "sync"
|
||||
|
||||
// Broadcaster fans a string message out to all SSE subscribers. Slow
|
||||
// subscribers drop messages rather than blocking publishers.
|
||||
type Broadcaster struct {
|
||||
mu sync.Mutex
|
||||
subs map[chan string]struct{}
|
||||
}
|
||||
|
||||
func NewBroadcaster() *Broadcaster {
|
||||
return &Broadcaster{subs: make(map[chan string]struct{})}
|
||||
}
|
||||
|
||||
func (b *Broadcaster) Subscribe() chan string {
|
||||
ch := make(chan string, 8)
|
||||
b.mu.Lock()
|
||||
b.subs[ch] = struct{}{}
|
||||
b.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *Broadcaster) Unsubscribe(ch chan string) {
|
||||
b.mu.Lock()
|
||||
if _, ok := b.subs[ch]; ok {
|
||||
delete(b.subs, ch)
|
||||
close(ch)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
}
|
||||
|
||||
func (b *Broadcaster) Publish(msg string) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for ch := range b.subs {
|
||||
select {
|
||||
case ch <- msg:
|
||||
default: // drop for slow subscriber
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user