forked from improbable-eng/go-httpwares
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wrapped_body.go
53 lines (45 loc) · 947 Bytes
/
wrapped_body.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
// Copyright 2017 Mark Nevill. All Rights Reserved.
// See LICENSE for licensing terms.
package http_metrics
import "io"
func wrapBody(rc io.ReadCloser, done func(int)) io.ReadCloser {
wrapped := &body{
parent: rc,
done: done,
}
if wt, ok := rc.(io.WriterTo); ok {
return bodyWT{body: wrapped, wt: wt}
}
return wrapped
}
type body struct {
parent io.ReadCloser
size int
done func(int)
}
type bodyWT struct {
*body
wt io.WriterTo
}
func (b *body) Read(p []byte) (int, error) {
n, err := b.parent.Read(p)
b.size += n
if err == io.EOF || err == io.ErrUnexpectedEOF {
b.done(b.size)
b.done = func(int) {}
}
return n, err
}
func (b *body) Close() error {
b.done(b.size)
return b.parent.Close()
}
func (b bodyWT) WriteTo(w io.Writer) (int64, error) {
n, err := b.wt.WriteTo(w)
b.body.size += int(n)
if err == io.EOF || err == io.ErrUnexpectedEOF {
b.done(b.size)
b.done = func(int) {}
}
return n, err
}