-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathresponse_writer.go
104 lines (90 loc) · 2.05 KB
/
response_writer.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
package neko
import (
"bufio"
"errors"
"log"
"net"
"net/http"
)
const noWritten = -1
type (
ResponseWriter interface {
http.ResponseWriter
http.Flusher
Status() int
// Size returns the size of the response body.
Size() int
Written() bool
WriteHeaderNow()
// Before allows for a function to be called before the ResponseWriter has been written to. This is
// useful for setting headers or any other operations that must happen before a response has been written.
Before(func(ResponseWriter))
}
writer struct {
http.ResponseWriter
status int
size int
beforeFuncs []beforeFunc
}
beforeFunc func(ResponseWriter)
)
func (c *writer) Status() int {
return c.status
}
func (c *writer) Size() int {
return c.size
}
func (c *writer) Written() bool {
return c.size != noWritten
}
func (c *writer) WriteHeaderNow() {
if !c.Written() {
c.size = 0
c.callBefore()
c.ResponseWriter.WriteHeader(c.status)
}
}
func (c *writer) Before(before func(ResponseWriter)) {
c.beforeFuncs = append(c.beforeFuncs, before)
}
func (c *writer) Write(data []byte) (size int, err error) {
c.WriteHeaderNow()
size, err = c.ResponseWriter.Write(data)
c.size += size
return
}
func (c *writer) WriteHeader(code int) {
if code > 0 {
c.status = code
if c.Written() {
log.Println("[NEKO] WARNING. Headers were already written!")
}
}
}
func (c *writer) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := c.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")
}
return hijacker.Hijack()
}
func (c *writer) CloseNotify() <-chan bool {
return c.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
func (c *writer) Flush() {
flusher, ok := c.ResponseWriter.(http.Flusher)
if ok {
flusher.Flush()
}
}
func (c *writer) callBefore() {
for i := len(c.beforeFuncs) - 1; i >= 0; i-- {
c.beforeFuncs[i](c)
}
}
func (c *writer) reset(writer http.ResponseWriter) {
c.ResponseWriter = writer
c.status = http.StatusOK
c.beforeFuncs = nil
c.size = noWritten
}