/
iocounter.go
79 lines (65 loc) · 1.39 KB
/
iocounter.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
package node
import (
"errors"
"io"
"net/http"
)
var (
ErrSizeCapExceeded = errors.New("body size cap exceeded")
)
const (
allowance = 16 * 1024
)
// ingressCounter is a wrapper for the underlying http.Request.Body and counts
// number of bytes consumed from it.
type ingressCounter struct {
body io.ReadCloser
maxSize int
sz int
}
func newIngressCounter(body io.ReadCloser, maxSize int) *ingressCounter {
return &ingressCounter{
body: body,
maxSize: maxSize,
sz: 0,
}
}
func (c *ingressCounter) Read(p []byte) (int, error) {
n, err := c.body.Read(p)
c.sz += n
if c.maxSize > 0 && c.sz > c.maxSize+allowance {
return 0, ErrSizeCapExceeded
}
return n, err
}
func (c *ingressCounter) Close() error {
return c.body.Close()
}
func (c *ingressCounter) size() int {
return c.sz
}
// egressCounter is a wrapper for the underlying http.ResponseWriter and counts
// number of bytes written to it.
type egressCounter struct {
w http.ResponseWriter
sz int
}
func newEgressCounter(w http.ResponseWriter) *egressCounter {
return &egressCounter{
w: w,
sz: 0,
}
}
func (c *egressCounter) Header() http.Header {
return c.w.Header()
}
func (c *egressCounter) Write(data []byte) (int, error) {
c.sz += len(data)
return c.w.Write(data)
}
func (c *egressCounter) WriteHeader(statusCode int) {
c.w.WriteHeader(statusCode)
}
func (c *egressCounter) size() int {
return c.sz
}