Refactored project structure
This commit is contained in:
45
backend/handlers/broker.go
Normal file
45
backend/handlers/broker.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import "log"
|
||||
|
||||
type Broker struct {
|
||||
clients map[chan []byte]bool
|
||||
add chan chan []byte
|
||||
remove chan chan []byte
|
||||
broadcast chan []byte
|
||||
}
|
||||
|
||||
func NewBroker() *Broker {
|
||||
b := &Broker{
|
||||
clients: make(map[chan []byte]bool),
|
||||
add: make(chan chan []byte),
|
||||
remove: make(chan chan []byte),
|
||||
broadcast: make(chan []byte),
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case c := <-b.add:
|
||||
b.clients[c] = true
|
||||
log.Printf("SSE client added. Total: %d", len(b.clients))
|
||||
case c := <-b.remove:
|
||||
if _, ok := b.clients[c]; ok {
|
||||
delete(b.clients, c)
|
||||
close(c)
|
||||
log.Printf("SSE client removed. Total: %d", len(b.clients))
|
||||
}
|
||||
case msg := <-b.broadcast:
|
||||
log.Printf("Broker broadcasting to %d clients", len(b.clients))
|
||||
for c := range b.clients {
|
||||
select {
|
||||
case c <- msg:
|
||||
log.Println("Message queued for client")
|
||||
default:
|
||||
log.Println("Client channel full, skipping")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return b
|
||||
}
|
||||
Reference in New Issue
Block a user