This repository has been archived by the owner on Feb 27, 2020. It is now read-only.
/
watchpipe.go
83 lines (68 loc) · 1.66 KB
/
watchpipe.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
package ioext
import (
"io"
"sync"
)
type watchPipe struct {
pipe io.ReadWriteCloser
m sync.Mutex
onClose func(error)
}
// WatchPipe will wrap an io.ReadWriteCloser such that onClose is called when
// the first read or write error happens, or after close() is called.
//
// The onClose callback will be called with the error from read, write or close.
// To allow for locking for example to remove the pipe from a list when closed,
// the onClose callback is always called on in separate go-routine.
func WatchPipe(pipe io.ReadWriteCloser, onClose func(error)) io.ReadWriteCloser {
return &watchPipe{
pipe: pipe,
onClose: onClose,
}
}
func (p *watchPipe) Read(b []byte) (int, error) {
n, err := p.pipe.Read(b)
// If there was an error we should call onClose
if err != nil {
// Take onClose (so we only call it once)
p.m.Lock()
onClose := p.onClose
p.onClose = nil
p.m.Unlock()
// Call onClose, if we were able to take it
if onClose != nil {
go onClose(err)
}
}
return n, err
}
func (p *watchPipe) Write(b []byte) (int, error) {
n, err := p.pipe.Write(b)
// If there was an error we should call onClose
if err != nil {
// Take onClose (so we only call it once)
p.m.Lock()
onClose := p.onClose
p.onClose = nil
p.m.Unlock()
// Call onClose, if we were able to take it
if onClose != nil {
go onClose(err)
}
}
return n, err
}
func (p *watchPipe) Close() error {
// Close underlying pipe
err := p.pipe.Close()
// Take onClose (so we only call it once)
p.m.Lock()
onClose := p.onClose
p.onClose = nil
p.m.Unlock()
// Call onClose, if we were able to take it
if onClose != nil {
go onClose(err)
}
return err
}