-
Notifications
You must be signed in to change notification settings - Fork 4
/
writecounter.go
66 lines (54 loc) · 1.3 KB
/
writecounter.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
package cutil
import (
"bufio"
"fmt"
"net"
"net/http"
"sync/atomic"
"time"
"github.com/pkg/errors"
)
type WriteCounter struct {
http.ResponseWriter
count int64
started time.Time
statusCode int
}
func NewWriteCounter(w http.ResponseWriter) *WriteCounter {
return &WriteCounter{
ResponseWriter: w,
started: time.Now(),
}
}
func (w *WriteCounter) Write(buf []byte) (int, error) {
n, err := w.ResponseWriter.Write(buf)
atomic.AddInt64(&w.count, int64(n))
return n, err
}
func (w *WriteCounter) Header() http.Header {
return w.ResponseWriter.Header()
}
func (w *WriteCounter) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.Header().Set("X-Runtime", fmt.Sprintf("%.6f", time.Since(w.started).Seconds()))
w.ResponseWriter.WriteHeader(statusCode)
}
func (w *WriteCounter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.Errorf("can't process response of type [%T]", w.ResponseWriter)
}
return h.Hijack()
}
func (w *WriteCounter) Count() int64 {
return atomic.LoadInt64(&w.count)
}
func (w *WriteCounter) Started() time.Time {
return w.started
}
func (w *WriteCounter) StatusCode() int {
return w.statusCode
}
func (w *WriteCounter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}