/
throttledreader.go
73 lines (56 loc) · 1.21 KB
/
throttledreader.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
package common
import (
"io"
"time"
)
type throttledReader struct {
reader io.Reader
bytesPerSecs int
lastSec time.Time
lastSecRead int
}
func (this *throttledReader) Read(p []byte) (n int, err error) {
if this.bytesPerSecs == 0 {
return this.reader.Read(p)
}
lenP := len(p)
index := 0
curSec := time.Now().Truncate(time.Second)
if this.lastSec.IsZero() || this.lastSec.Before(curSec) {
this.lastSec = curSec
this.lastSecRead = 0
}
for {
sleep := false
remainAllowedLen := this.bytesPerSecs - this.lastSecRead
remainBufferLen := lenP - index
if remainBufferLen > remainAllowedLen {
remainBufferLen = remainAllowedLen
sleep = true
}
n, err := this.reader.Read(p[index : index+remainBufferLen])
index += n
this.lastSecRead += n
if Error(nil) {
return index, err
}
if sleep {
this.lastSec = this.lastSec.Add(time.Second)
this.lastSecRead = 0
d := this.lastSec.Sub(time.Now())
if d > 0 {
time.Sleep(d)
}
}
if index == Min(this.bytesPerSecs, lenP) {
return index, nil
}
}
}
func NewThrottledReader(reader io.Reader, bytesPerSecs int) io.Reader {
r := &throttledReader{
reader: reader,
bytesPerSecs: bytesPerSecs,
}
return r
}