forked from jfrog/jfrog-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writers.go
59 lines (53 loc) · 1.28 KB
/
writers.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
package utils
import (
"errors"
"io"
"sync"
)
var ErrShortWrite = errors.New("short write")
type asyncMultiWriter struct {
writers []io.Writer
}
// Async MultiWriter creates a writer that duplicates its writes to all the
// provided writers asynchronous
func AsyncMultiWriter(writers ...io.Writer) io.Writer {
w := make([]io.Writer, len(writers))
copy(w, writers)
return &asyncMultiWriter{w}
}
// write data asynchronous by each writer and wait for go routine to complete
// in case of an error write will not complete
func (t *asyncMultiWriter) Write(p []byte) (int, error) {
var wg sync.WaitGroup
wg.Add(len(t.writers))
errChannel := make(chan error)
finished := make(chan bool, 1)
for _, w := range t.writers {
/* write data in async */
go writeData(p, w, &wg, errChannel)
}
/* wait group in the go routine we ensure either all pass */
go func() {
wg.Wait()
close(finished)
}()
/* This select will block until one of the two channels returns a value. */
select {
case <-finished:
case err := <-errChannel:
if err != nil {
return 0, err
}
}
return len(p), nil
}
func writeData(p []byte, w io.Writer, wg *sync.WaitGroup, errChan chan error) {
n, err := w.Write(p)
if err != nil {
errChan <- err
}
if n != len(p) {
errChan <- ErrShortWrite
}
wg.Done()
}