-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbroadcaster.go
More file actions
70 lines (58 loc) · 1.16 KB
/
Copy pathbroadcaster.go
File metadata and controls
70 lines (58 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// MIT License
// Copyright (c) 2025 Pooyan Khanjankhani
package main
import (
"io"
"sync"
)
type Broadcaster struct {
mu sync.RWMutex
writers map[io.WriteCloser]struct{}
}
func NewBroadcaster() *Broadcaster {
return &Broadcaster{
writers: make(map[io.WriteCloser]struct{}),
}
}
func (this *Broadcaster) Add(w io.WriteCloser) {
this.mu.Lock()
this.writers[w] = struct{}{}
this.mu.Unlock()
}
func (this *Broadcaster) Remove(w io.WriteCloser) {
this.mu.Lock()
this.remove(w)
this.mu.Unlock()
}
func (this *Broadcaster) Write(p []byte) (n int, err error) {
this.mu.RLock()
removing := make([]io.WriteCloser, 0)
l := len(p)
for w := range this.writers {
n, e := w.Write(p)
if e != nil || n < l {
removing = append(removing, w)
}
}
this.mu.RUnlock()
for _, w := range removing {
this.Remove(w)
}
return l, nil
}
func (this *Broadcaster) Run(r io.Reader) error {
_, err := io.Copy(this, r)
this.removeAll()
return err
}
func (this *Broadcaster) removeAll() {
this.mu.Lock()
defer this.mu.Unlock()
for w := range this.writers {
this.remove(w)
}
}
func (this *Broadcaster) remove(w io.WriteCloser) {
w.Close()
delete(this.writers, w)
}