-
Notifications
You must be signed in to change notification settings - Fork 9
/
response_writer.go
70 lines (59 loc) · 1.89 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
package datacounter
import (
"bufio"
"fmt"
"net"
"net/http"
"sync/atomic"
"time"
)
// ResponseWriterCounter is counter for http.ResponseWriter
type ResponseWriterCounter struct {
http.ResponseWriter
count uint64
started time.Time
statusCode int
}
// NewResponseWriterCounter function create new ResponseWriterCounter
func NewResponseWriterCounter(rw http.ResponseWriter) *ResponseWriterCounter {
return &ResponseWriterCounter{
ResponseWriter: rw,
started: time.Now(),
}
}
// Write returns underlying Write result, while counting data size
func (counter *ResponseWriterCounter) Write(buf []byte) (int, error) {
n, err := counter.ResponseWriter.Write(buf)
atomic.AddUint64(&counter.count, uint64(n))
return n, err
}
// Header returns underlying Header result
func (counter *ResponseWriterCounter) Header() http.Header {
return counter.ResponseWriter.Header()
}
// WriteHeader returns underlying WriteHeader, while setting Runtime header
func (counter *ResponseWriterCounter) WriteHeader(statusCode int) {
counter.statusCode = statusCode
counter.Header().Set("X-Runtime", fmt.Sprintf("%.6f", time.Since(counter.started).Seconds()))
counter.ResponseWriter.WriteHeader(statusCode)
}
// Hijack returns underlying Hijack
func (counter *ResponseWriterCounter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return counter.ResponseWriter.(http.Hijacker).Hijack()
}
// Count function return counted bytes
func (counter *ResponseWriterCounter) Count() uint64 {
return atomic.LoadUint64(&counter.count)
}
// Started returns started value
func (counter *ResponseWriterCounter) Started() time.Time {
return counter.started
}
// StatusCode returns sent status code
func (counter *ResponseWriterCounter) StatusCode() int {
return counter.statusCode
}
// Unwrap returns the underlying ResponseWriter
func (counter *ResponseWriterCounter) Unwrap() http.ResponseWriter {
return counter.ResponseWriter
}