forked from remind101/conveyor
/
http.go
62 lines (54 loc) · 1.5 KB
/
http.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
// Package http provides streaming implementations of various net/http types.
package http
import (
"errors"
"io"
"net/http"
)
// ResponseWriter provides an implementation of the http.ResponseWriter
// interface that is unbuffered. Every call to write will be flushed to the
// underyling connection and streamed to the client.
type ResponseWriter struct {
http.ResponseWriter
w io.Writer
}
// StreamingResponseWriter wraps the http.ResponseWriter with unbuffered
// streaming. If the provided ResponseWriter does not implement http.Flusher,
// this function will panic.
func StreamingResponseWriter(w http.ResponseWriter) *ResponseWriter {
fw, err := newFlushWriter(w)
if err != nil {
panic(err)
}
return &ResponseWriter{
ResponseWriter: w,
w: fw,
}
}
// Write delegates to the underlying flushWriter to perform the write and flush
// it to the connection.
func (w *ResponseWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
}
// flushWriter is an io.Writer implementation that flushes to the underlying
// io.Writer whenever Write is called.
type flushWriter struct {
f http.Flusher
w io.Writer
}
func newFlushWriter(w http.ResponseWriter) (*flushWriter, error) {
fw := &flushWriter{w: w}
if f, ok := w.(http.Flusher); ok {
fw.f = f
} else {
return fw, errors.New("provided http.ResponseWriter does not implement http.Flusher")
}
return fw, nil
}
func (fw *flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if fw.f != nil {
fw.f.Flush()
}
return
}