-
Notifications
You must be signed in to change notification settings - Fork 179
/
stream.go
61 lines (50 loc) · 827 Bytes
/
stream.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
package helpers
import (
"io"
"net/http"
)
type ReadWriter struct {
io.Reader
io.Writer
}
func Pipe(a, b io.ReadWriter) error {
ch := make(chan error)
go halfPipe(a, b, ch)
go halfPipe(b, a, ch)
if err := <-ch; err != nil {
return err
}
if err := <-ch; err != nil {
return err
}
return nil
}
func halfPipe(w io.Writer, r io.Reader, ch chan error) {
ch <- Stream(w, r)
if c, ok := w.(io.Closer); ok {
c.Close()
}
}
func Stream(w io.Writer, r io.Reader) error {
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if n > 0 {
if _, err := w.Write(buf[0:n]); err != nil {
if err == io.ErrClosedPipe {
return nil
}
return err
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
}