-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathcapture.go
42 lines (36 loc) Β· 1.11 KB
/
capture.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
package middleware
import (
"bufio"
"fmt"
"net"
"net/http"
)
// ResponseCapture is a http.ResponseWriter which captures the response status
// code and content length.
type ResponseCapture struct {
http.ResponseWriter
StatusCode int
ContentLength int
}
// CaptureResponse creates a ResponseCapture that wraps the given ResponseWriter.
func CaptureResponse(w http.ResponseWriter) *ResponseCapture {
return &ResponseCapture{ResponseWriter: w}
}
// WriteHeader records the value of the status code before writing it.
func (w *ResponseCapture) WriteHeader(code int) {
w.StatusCode = code
w.ResponseWriter.WriteHeader(code)
}
// Write computes the written len and stores it in ContentLength.
func (w *ResponseCapture) Write(b []byte) (int, error) {
n, err := w.ResponseWriter.Write(b)
w.ContentLength += n
return n, err
}
// Hijack supports the http.Hijacker interface.
func (w *ResponseCapture) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := w.ResponseWriter.(http.Hijacker); ok {
return h.Hijack()
}
return nil, nil, fmt.Errorf("response writer does not support hijacking: %T", w.ResponseWriter)
}