fork/gdu
git clone https://git.julia.blue/fork/gdu
d672bf4
subvolume
1package webui 2 3import "sync" 4 5// hub is a minimal Server-Sent Events broadcaster. Subscribers register a 6// buffered channel and receive the latest status messages. The most recent 7// message is retained so newly connected clients get the current state at once. 8type hub struct { 9mu sync.Mutex 10subs map [chan string ]struct {} 11last string 12} 13 14func newHub ()* hub { 15return & hub {subs :make (map [chan string ]struct {})} 16} 17 18// subscribe registers a new subscriber and returns its channel plus the last 19// broadcast message (empty if none yet). 20func (h * hub )subscribe () (events chan string ,last string ) { 21events = make (chan string ,8 ) 22h .mu .Lock () 23h .subs [events ]= struct {}{} 24last = h .last 25h .mu .Unlock () 26return events ,last 27} 28 29// unsubscribe removes a subscriber and closes its channel. 30func (h * hub )unsubscribe (ch chan string ) { 31h .mu .Lock () 32if _ ,ok := h .subs [ch ];ok { 33delete (h .subs ,ch ) 34close (ch ) 35 } 36h .mu .Unlock () 37} 38 39// publish stores the message as the latest state and delivers it to every 40// subscriber without blocking on slow consumers. 41func (h * hub )publish (msg string ) { 42h .mu .Lock () 43h .last = msg 44for ch := range h .subs { 45select { 46case ch <- msg : 47default : 48 } 49 } 50h .mu .Unlock () 51}