-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse_streamer.go
77 lines (66 loc) · 1.8 KB
/
response_streamer.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
package negronicache
import (
"net/http"
"io/ioutil"
"gopkg.in/djherbis/stream.v1"
)
type ResponseStreamer struct {
StatusCode int
http.ResponseWriter
*stream.Stream
// C will be closed by WriteHeader to signal the headers' writing
C chan struct{}
}
func NewResponseStreamer(w http.ResponseWriter) *ResponseStreamer {
strm, err := stream.NewStream("responseBuffer", stream.NewMemFS())
if err != nil {
panic(err)
}
return &ResponseStreamer{
ResponseWriter: w,
Stream: strm,
C: make(chan struct{}),
}
}
// WaitHeaders returns iff and when WriteHeader has been called.
func (rs *ResponseStreamer) WaitHeaders() {
for range rs.C {
}
}
func(rs *ResponseStreamer) WriteHeader(status int) {
defer close(rs.C)
rs.StatusCode = status
rs.ResponseWriter.WriteHeader(status)
}
func(rs *ResponseStreamer) Write(b []byte) (int, error) {
rs.Stream.Write(b)
return rs.ResponseWriter.Write(b)
}
func(rs *ResponseStreamer) Close() error {
return rs.Stream.Close()
}
// Resource returns a copy of the responseStreamer as a Resource object
func (rs *ResponseStreamer) Resource() *Resource {
r, err := rs.Stream.NextReader()
if err == nil {
b, err := ioutil.ReadAll(r)
r.Close()
if err == nil {
return NewResourceBytes(rs.StatusCode, b, rs.Header())
}
}
return &Resource{
header: rs.Header(),
statusCode: rs.StatusCode,
ReadSeekCloser: errReadSeekCloser{err},
}
}
type errReadSeekCloser struct {
err error
}
func (e errReadSeekCloser) Error() string {
return e.err.Error()
}
func (e errReadSeekCloser) Close() error { return e.err }
func (e errReadSeekCloser) Read(_ []byte) (int, error) { return 0, e.err }
func (e errReadSeekCloser) Seek(_ int64, _ int) (int64, error) { return 0, e.err }