-
Notifications
You must be signed in to change notification settings - Fork 0
/
readcloser.go
59 lines (52 loc) · 917 Bytes
/
readcloser.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
package raterw
import (
"context"
"io"
"golang.org/x/time/rate"
)
func NewRateReadCloser(r io.ReadCloser, l rate.Limit, burst int) io.ReadCloser {
return &RateReadCloser{
R: r,
L: rate.NewLimiter(l, burst),
}
}
func AddRateReadCloser(r io.ReadCloser, l *rate.Limiter) io.ReadCloser {
return &RateReadCloser{
R: r,
L: l,
}
}
type RateReadCloser struct {
R io.ReadCloser
L *rate.Limiter
}
func (r *RateReadCloser) Close() error {
return r.R.Close()
}
func (r *RateReadCloser) Read(p []byte) (n int, err error) {
lenp := len(p)
ctx := context.Background()
burst := r.L.Burst()
b := make([]byte, burst)
for {
size := lenp - n
if size < burst {
b = b[:size]
} else {
size = burst
}
err = r.L.WaitN(ctx, size)
if err != nil {
return
}
var num int
num, err = r.R.Read(b)
n += copy(p[n:], b[:num])
if n == lenp {
return
}
if err != nil {
return
}
}
}