-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
92 lines (78 loc) · 1.67 KB
/
response.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
package potgo
import (
"bufio"
"net"
"net/http"
)
const (
defaultStatus = http.StatusOK
noWritten = -1
)
// Response 包装一个 http.ResponseWriter 并实现其要使用的接口
type Response struct {
Writer http.ResponseWriter
status int
size int
}
// reset 重置 Response
func (res *Response) reset(writer http.ResponseWriter) {
res.Writer = writer
res.size = noWritten
res.status = defaultStatus
}
// Reset 重置 Response
func (res *Response) Reset(w http.ResponseWriter) bool {
if res.Written() {
return false
}
h := w.Header()
for k := range h {
h[k] = nil
}
res.reset(w)
return true
}
// Size 返回写入数据的大小
func (res *Response) Size() int {
return res.size
}
// Status 返回状态码
func (res *Response) Status() int {
return res.status
}
// WriteHeader 发送 HTTP status code
func (res *Response) WriteHeader(code int) {
if code > 0 && res.status != code {
res.status = code
}
}
// Written 是否已经向客户端写入数据
func (res *Response) Written() bool {
return res.size > noWritten
}
// Write 向客户端写入回复的数据
func (res *Response) Write(b []byte) (int, error) {
res.tryWriteHeader()
n, err := res.Writer.Write(b)
res.size += n
return n, err
}
func (res *Response) tryWriteHeader() {
if !res.Written() {
res.size = 0
if res.status == 0 {
res.status = defaultStatus
}
res.Writer.WriteHeader(res.status)
}
}
// Flush 刷新输出缓冲
func (res *Response) Flush() {
if flusher, ok := res.Writer.(http.Flusher); ok {
flusher.Flush()
}
}
// Hijack 实现 http.Hijacker 接口
func (res *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return res.Writer.(http.Hijacker).Hijack()
}