forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
98 lines (80 loc) · 2.26 KB
/
io.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"io"
"net/http"
"sync"
"github.com/prometheus/client_golang/prometheus"
)
// statResponseWriter collects the amount of bytes written.
//
// The wrapped ResponseWriter must implement http.CloseNotifier.
//
// Additionally it caches response status code.
type statResponseWriter struct {
http.ResponseWriter
statusCode int
// wroteHeader tells whether the header's been written to
// the original ResponseWriter
wroteHeader bool
bytesWritten prometheus.Counter
}
func (rw *statResponseWriter) Write(b []byte) (int, error) {
if rw.statusCode == 0 {
rw.statusCode = http.StatusOK
}
if !rw.wroteHeader {
rw.ResponseWriter.WriteHeader(rw.statusCode)
rw.wroteHeader = true
}
n, err := rw.ResponseWriter.Write(b)
rw.bytesWritten.Add(float64(n))
return n, err
}
func (rw *statResponseWriter) WriteHeader(statusCode int) {
// cache statusCode to keep the opportunity to change it in further
rw.statusCode = statusCode
}
// CloseNotify implements http.CloseNotifier
func (rw *statResponseWriter) CloseNotify() <-chan bool {
// The rw.ResponseWriter must implement http.CloseNotifier
return rw.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
// statReadCloser collects the amount of bytes read.
type statReadCloser struct {
io.ReadCloser
bytesRead prometheus.Counter
}
func (src *statReadCloser) Read(p []byte) (int, error) {
n, err := src.ReadCloser.Read(p)
src.bytesRead.Add(float64(n))
return n, err
}
// cachedReadCloser caches the first 1Kb form the wrapped ReadCloser.
type cachedReadCloser struct {
io.ReadCloser
// bLock protects b from concurrent access when Read and String
// are called from concurrent goroutines.
bLock sync.Mutex
// b holds up to 1Kb of the initial data read from ReadCloser.
b []byte
}
func (crc *cachedReadCloser) Read(p []byte) (int, error) {
n, err := crc.ReadCloser.Read(p)
crc.bLock.Lock()
if len(crc.b) < 1024 {
crc.b = append(crc.b, p[:n]...)
if len(crc.b) >= 1024 {
crc.b = append(crc.b[:1024], "..."...)
}
}
crc.bLock.Unlock()
// Do not cache the last read operation, since it slows down
// reading large amounts of data such as large INSERT queries.
return n, err
}
func (crc *cachedReadCloser) String() string {
crc.bLock.Lock()
s := string(crc.b)
crc.bLock.Unlock()
return s
}