fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: add web UI (#617)d672bf4

ignore
1.2 KiB51 linesraw
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 {
9	mu   sync.Mutex
10	subs map[chan string]struct{}
11	last string
12}
13
14func newHub() *hub {
15	return &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) {
21	events = make(chan string, 8)
22	h.mu.Lock()
23	h.subs[events] = struct{}{}
24	last = h.last
25	h.mu.Unlock()
26	return events, last
27}
28
29// unsubscribe removes a subscriber and closes its channel.
30func (h *hub) unsubscribe(ch chan string) {
31	h.mu.Lock()
32	if _, ok := h.subs[ch]; ok {
33		delete(h.subs, ch)
34		close(ch)
35	}
36	h.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) {
42	h.mu.Lock()
43	h.last = msg
44	for ch := range h.subs {
45		select {
46		case ch <- msg:
47		default:
48		}
49	}
50	h.mu.Unlock()
51}