-
Notifications
You must be signed in to change notification settings - Fork 3
/
multi_writer.go
88 lines (79 loc) · 1.89 KB
/
multi_writer.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"io"
"sync"
)
func (t *multiWriter) Remove(writers ...io.Writer) {
t.mu.Lock()
defer t.mu.Unlock()
for i := len(t.writers) - 1; i > 0; i-- {
for _, v := range writers {
if t.writers[i] == v {
t.writers = append(t.writers[:i], t.writers[i+1:]...)
break
}
}
}
}
func (t *multiWriter) Append(writers ...io.Writer) {
t.mu.Lock()
defer t.mu.Unlock()
t.writers = append(t.writers, writers...)
}
type multiWriter struct {
writers []io.Writer
mu sync.Mutex
}
func (t *multiWriter) Write(p []byte) (n int, err error) {
t.mu.Lock()
defer t.mu.Unlock()
for _, w := range t.writers {
n, err = w.Write(p)
if err != nil {
return
}
if n != len(p) {
err = io.ErrShortWrite
return
}
}
return len(p), nil
}
// ConcurrentWrite will write to all writers concurrently, however this may be bad because it spawns potentially hundreds of goroutines a second.
// Source: https://gist.github.com/alexmullins/1c6cc6dc38a8e83ed2f6
func (t *multiWriter) ConcurrentWrite(p []byte) (n int, err error) {
type data struct {
n int
err error
}
results := make(chan data)
for _, w := range t.writers {
go func(wr io.Writer, p []byte, ch chan data) {
n, err = wr.Write(p)
// We can remove writers easily when they fail here, but that doesn't let us tell the orchestrator things are no longer working
if err != nil {
ch <- data{n, err}
return
}
if n != len(p) {
ch <- data{n, io.ErrShortWrite}
return
}
ch <- data{n, nil} //completed ok
}(w, p, results)
}
for range t.writers {
d := <-results
if d.err != nil {
return d.n, d.err
}
}
return len(p), nil
}
// MultiWriter creates a writer that duplicates its writes to all the
// provided writers, similar to the Unix tee(1) command.
func MultiWriter(writers ...io.Writer) io.Writer {
w := make([]io.Writer, len(writers))
copy(w, writers)
return &multiWriter{writers: w}
}