-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponseWriter.go
64 lines (53 loc) · 1.23 KB
/
responseWriter.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
package watch
import (
"bufio"
"fmt"
"net"
"net/http"
)
type customResponseWriter struct {
http.ResponseWriter
writes [][]byte
status int
}
func (rw *customResponseWriter) Write(b []byte) (int, error) {
// Pretending that there is no error :(
rw.writes = append(rw.writes, b)
return len(b), nil
}
func (rw *customResponseWriter) WriteHeader(statusCode int) {
// if already set, throw error
if rw.status != 0 {
panic(fmt.Sprintf("Status code %d already exists", rw.status))
}
rw.status = statusCode
}
// Flushes data and headers to original writer
func (rw *customResponseWriter) flush() error {
if rw.status != 0 {
rw.ResponseWriter.WriteHeader(rw.status)
}
for _, write := range rw.writes {
_, err := rw.ResponseWriter.Write(write)
if err != nil {
return err
}
}
return nil
}
func (rw *customResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := rw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("the ResponseWriter does not support Hijacker Interface")
}
return hijacker.Hijack()
}
func (rw *customResponseWriter) Flush() {
flusher, ok := rw.ResponseWriter.(http.Flusher)
if ok {
if rw.status == 0 {
rw.WriteHeader(http.StatusOK)
}
flusher.Flush()
}
}