-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathresponse.go
More file actions
67 lines (56 loc) · 1.22 KB
/
response.go
File metadata and controls
67 lines (56 loc) · 1.22 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
package kocha
import (
"io"
"net/http"
"net/http/httptest"
"sync"
)
var (
_ http.ResponseWriter = &Response{}
responsePool = &sync.Pool{
New: func() interface{} {
return &Response{}
},
}
)
// Response represents a response.
type Response struct {
http.ResponseWriter
ContentType string
StatusCode int
cookies []*http.Cookie
resp *httptest.ResponseRecorder
}
// newResponse returns a new Response that responds to rw.
func newResponse() *Response {
r := responsePool.Get().(*Response)
r.reset()
r.ContentType = ""
r.cookies = r.cookies[:0]
return r
}
// Cookies returns a slice of *http.Cookie.
func (r *Response) Cookies() []*http.Cookie {
return r.cookies
}
// SetCookie adds a Set-Cookie header to the response.
func (r *Response) SetCookie(cookie *http.Cookie) {
r.cookies = append(r.cookies, cookie)
http.SetCookie(r, cookie)
}
func (r *Response) writeTo(w http.ResponseWriter) error {
for key, values := range r.Header() {
for _, v := range values {
w.Header().Add(key, v)
}
}
w.WriteHeader(r.resp.Code)
_, err := io.Copy(w, r.resp.Body)
responsePool.Put(r)
return err
}
func (r *Response) reset() {
r.StatusCode = http.StatusOK
r.resp = httptest.NewRecorder()
r.ResponseWriter = r.resp
}