-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext_response_writer.go
More file actions
71 lines (59 loc) · 1.4 KB
/
context_response_writer.go
File metadata and controls
71 lines (59 loc) · 1.4 KB
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
package navaros
import (
"bufio"
"net"
"net/http"
)
type ContextResponseWriter struct {
ctx *Context
bodyWriter http.ResponseWriter
}
var _ http.ResponseWriter = &ContextResponseWriter{}
var _ http.Flusher = &ContextResponseWriter{}
var _ http.Hijacker = &ContextResponseWriter{}
func (c *ContextResponseWriter) Header() http.Header {
return c.bodyWriter.Header()
}
func (c *ContextResponseWriter) WriteHeader(status int) {
c.ctx.Status = status
c.flushHeaders()
}
func (c *ContextResponseWriter) Write(bytes []byte) (int, error) {
c.ctx.hasWrittenBody = true
c.flushHeaders()
return c.bodyWriter.Write(bytes)
}
func (c *ContextResponseWriter) Flush() {
if f, ok := c.bodyWriter.(http.Flusher); ok {
f.Flush()
}
}
func (c *ContextResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := c.bodyWriter.(http.Hijacker)
if !ok {
return nil, nil, http.ErrNotSupported
}
return hijacker.Hijack()
}
func (c *ContextResponseWriter) flushHeaders() {
if c.ctx.hasWrittenHeaders {
return
}
c.ctx.hasWrittenHeaders = true
for key, values := range c.ctx.Headers {
for _, value := range values {
c.bodyWriter.Header().Add(key, value)
}
}
for _, cookie := range c.ctx.Cookies {
http.SetCookie(c.bodyWriter, cookie)
}
if c.ctx.inhibitResponse {
return
}
status := c.ctx.Status
if status == 0 {
status = http.StatusOK
}
c.bodyWriter.WriteHeader(status)
}