-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathresp.go
74 lines (62 loc) · 1.33 KB
/
resp.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
package twig
import (
"bufio"
"io"
"net"
"net/http"
)
// ResponseWrap 包装http.ResponseWrite
type ResponseWrap struct {
Writer http.ResponseWriter
Status int
Committed bool
}
func newResponseWrap(w http.ResponseWriter) *ResponseWrap {
return &ResponseWrap{Writer: w}
}
func (r *ResponseWrap) Header() http.Header {
return r.Writer.Header()
}
func (r *ResponseWrap) Flush() {
r.Writer.(http.Flusher).Flush()
}
// 设置header时查是否已经输出内容
func (r *ResponseWrap) WriteHeader(code int) {
if r.Committed {
return
}
r.Status = code
r.Writer.WriteHeader(code)
r.Committed = true
}
// 输出时候检查是否设置Header
func (r *ResponseWrap) Write(b []byte) (n int, err error) {
if !r.Committed {
r.WriteHeader(OK)
}
n, err = r.Writer.Write(b)
return
}
func (r *ResponseWrap) ReadFrom(src io.Reader) (n int64, e error) {
if !r.Committed {
r.WriteHeader(OK)
}
n, e = io.Copy(r.Writer, src)
return
}
func (r *ResponseWrap) WriteString(str string) (n int, err error) {
if !r.Committed {
r.WriteHeader(OK)
}
n, err = io.WriteString(r.Writer, str)
return
}
// Hijack Hijack 支持
func (r *ResponseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.Writer.(http.Hijacker).Hijack()
}
func (r *ResponseWrap) reset(w http.ResponseWriter) {
r.Writer = w
r.Status = OK
r.Committed = false
}