-
Notifications
You must be signed in to change notification settings - Fork 582
/
response_writer_feature.go
107 lines (96 loc) · 2.5 KB
/
response_writer_feature.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package negroni
import (
"bufio"
"net"
"net/http"
)
const (
flusher = 1 << iota
hijacker
closeNotifier
)
type (
flusherFeature struct{ *responseWriter }
hijackerFeature struct{ *responseWriter }
closeNotifierFeature struct{ *responseWriter }
)
func (f flusherFeature) Flush() {
if !f.Written() {
// The status will be StatusOK if WriteHeader has not been called yet
f.WriteHeader(http.StatusOK)
}
f.ResponseWriter.(http.Flusher).Flush()
}
func (f hijackerFeature) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return f.ResponseWriter.(http.Hijacker).Hijack()
}
func (f closeNotifierFeature) CloseNotify() <-chan bool {
return f.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
var featurePicker = make([]func(writer *responseWriter) ResponseWriter, 8)
func initFeaturePicker() {
featurePicker[0] = func(w *responseWriter) ResponseWriter {
return w
}
featurePicker[flusher] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Flusher
}{w, flusherFeature{w}}
}
featurePicker[hijacker] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Hijacker
}{w, hijackerFeature{w}}
}
featurePicker[closeNotifier] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Flusher
}{w, flusherFeature{w}}
}
featurePicker[flusher|hijacker] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Flusher
http.Hijacker
}{w, flusherFeature{w}, hijackerFeature{w}}
}
featurePicker[flusher|closeNotifier] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Flusher
http.CloseNotifier
}{w, flusherFeature{w}, closeNotifierFeature{w}}
}
featurePicker[hijacker|closeNotifier] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Hijacker
http.CloseNotifier
}{w, hijackerFeature{w}, closeNotifierFeature{w}}
}
featurePicker[flusher|hijacker|closeNotifier] = func(w *responseWriter) ResponseWriter {
return struct {
*responseWriter
http.Flusher
http.Hijacker
http.CloseNotifier
}{w, flusherFeature{w}, hijackerFeature{w}, closeNotifierFeature{w}}
}
}
func wrapFeature(w *responseWriter) ResponseWriter {
rw := w.ResponseWriter
feature := 0
if _, ok := rw.(http.Flusher); ok {
feature |= flusher
}
if _, ok := rw.(http.Hijacker); ok {
feature |= hijacker
}
if _, ok := rw.(http.CloseNotifier); ok {
feature |= closeNotifier
}
return featurePicker[feature](w)
}