-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrite-closer.go
51 lines (38 loc) · 929 Bytes
/
write-closer.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
package main
import (
"bufio"
"fmt"
"io"
"go.uber.org/multierr"
)
type nopCloser struct{ io.Writer }
func (nopCloser) Close() (err error) { return }
type nopWriteCloser struct{}
func (nopWriteCloser) Write(p []byte) (n int, err error) { return len(p), nil }
func (nopWriteCloser) Close() (err error) { return }
var nopwc io.WriteCloser = nopWriteCloser{}
func MultiCopy(r io.Reader, writers ...io.WriteCloser) (err error) {
if len(writers) == 0 {
return
}
iow := []io.Writer{}
for _, w := range writers {
iow = append(iow, w)
}
mw := bufio.NewWriter(io.MultiWriter(iow...))
if _, err = io.Copy(mw, r); err != nil {
return fmt.Errorf("error copying: %w", err)
}
mw.Flush()
defer func() {
for _, w := range writers {
if errw := w.Close(); errw != nil {
err = multierr.Append(err, errw)
}
}
if err != nil {
err = fmt.Errorf("error closing writer(s) : %w", err)
}
}()
return
}