-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappend_writer.go
More file actions
64 lines (56 loc) · 1.16 KB
/
Copy pathappend_writer.go
File metadata and controls
64 lines (56 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
package fs
import "io"
// appendWriter implements append by streaming existing content followed by
// new writes. A background goroutine continuously drains the write buffer.
type appendWriter struct {
pr *io.PipeReader
pw *io.PipeWriter
w io.WriteCloser
done chan error
}
// newAppendWriter creates a writer that appends to existing content.
// r may be nil if there's no existing content.
func newAppendWriter(r io.ReadCloser, w io.WriteCloser) io.WriteCloser {
var (
pr, pw = io.Pipe()
aw = &appendWriter{
pr: pr,
pw: pw,
w: w,
done: make(chan error),
}
)
go func() {
var err error
if r != nil {
_, err = io.Copy(w, r)
closeErr := r.Close()
if err == nil {
err = closeErr
}
if err != nil {
pr.CloseWithError(err)
aw.done <- err
return
}
}
_, err = io.Copy(w, pr)
aw.done <- err
}()
return aw
}
func (aw *appendWriter) Write(p []byte) (n int, err error) {
return aw.pw.Write(p)
}
func (aw *appendWriter) Close() error {
pwErr := aw.pw.Close()
copyErr := <-aw.done
closeErr := aw.w.Close()
if pwErr != nil {
return pwErr
}
if copyErr != nil {
return copyErr
}
return closeErr
}