-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathproxywriter.go
96 lines (79 loc) · 1.82 KB
/
proxywriter.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
package mpb
import (
"io"
"time"
)
type proxyWriter struct {
io.WriteCloser
bar *Bar
}
func (x proxyWriter) Write(p []byte) (int, error) {
n, err := x.WriteCloser.Write(p)
x.bar.IncrBy(n)
return n, err
}
type proxyReaderFrom struct {
proxyWriter
}
func (x proxyReaderFrom) ReadFrom(r io.Reader) (int64, error) {
n, err := x.WriteCloser.(io.ReaderFrom).ReadFrom(r)
x.bar.IncrInt64(n)
return n, err
}
type ewmaProxyWriter struct {
io.WriteCloser
bar *Bar
}
func (x ewmaProxyWriter) Write(p []byte) (int, error) {
start := time.Now()
n, err := x.WriteCloser.Write(p)
x.bar.EwmaIncrBy(n, time.Since(start))
return n, err
}
type ewmaProxyReaderFrom struct {
ewmaProxyWriter
}
func (x ewmaProxyReaderFrom) ReadFrom(r io.Reader) (int64, error) {
start := time.Now()
n, err := x.WriteCloser.(io.ReaderFrom).ReadFrom(r)
x.bar.EwmaIncrInt64(n, time.Since(start))
return n, err
}
func newProxyWriter(w io.Writer, b *Bar, hasEwma bool) io.WriteCloser {
wc := toWriteCloser(w)
if hasEwma {
epw := ewmaProxyWriter{wc, b}
if _, ok := w.(io.ReaderFrom); ok {
return ewmaProxyReaderFrom{epw}
}
return epw
}
pw := proxyWriter{wc, b}
if _, ok := w.(io.ReaderFrom); ok {
return proxyReaderFrom{pw}
}
return pw
}
func toWriteCloser(w io.Writer) io.WriteCloser {
if wc, ok := w.(io.WriteCloser); ok {
return wc
}
return toNopWriteCloser(w)
}
func toNopWriteCloser(w io.Writer) io.WriteCloser {
if _, ok := w.(io.ReaderFrom); ok {
return nopWriteCloserReaderFrom{w}
}
return nopWriteCloser{w}
}
type nopWriteCloser struct {
io.Writer
}
func (nopWriteCloser) Close() error { return nil }
type nopWriteCloserReaderFrom struct {
io.Writer
}
func (nopWriteCloserReaderFrom) Close() error { return nil }
func (c nopWriteCloserReaderFrom) ReadFrom(r io.Reader) (int64, error) {
return c.Writer.(io.ReaderFrom).ReadFrom(r)
}