-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
64 lines (56 loc) · 1.24 KB
/
reader.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
package iorate
import (
"context"
"io"
"time"
"golang.org/x/time/rate"
)
type LimitReader struct {
r io.Reader
limiter *rate.Limiter
ctx context.Context
}
func (r *LimitReader) Read(p []byte) (n int, err error) {
if r.limiter == nil {
return r.r.Read(p)
}
n, err = r.r.Read(p)
if err != nil {
return
}
err = r.limiter.WaitN(r.ctx, n)
return n, err
}
func NewReader(r io.Reader, limit ...float64) *LimitReader {
reader := &LimitReader{
r: r,
ctx: context.Background(),
}
if len(limit) > 0 {
reader.limiter = rate.NewLimiter(rate.Limit(limit[0]), defaultBursts)
if res := reader.limiter.ReserveN(time.Now(), defaultBursts); res.OK() {
time.Sleep(res.Delay())
}
}
return reader
}
func NewReaderWithContext(r io.Reader, ctx context.Context, limit ...float64) *LimitReader {
reader := &LimitReader{
r: r,
ctx: ctx,
}
// 每秒限制数
if len(limit) > 0 {
reader.limiter = rate.NewLimiter(rate.Limit(limit[0]), defaultBursts)
}
return reader
}
func (r *LimitReader) SetLimit(limit float64) {
r.limiter = rate.NewLimiter(rate.Limit(limit), defaultBursts)
if res := r.limiter.ReserveN(time.Now(), defaultBursts); res.OK() {
time.Sleep(res.Delay())
}
}
func (r *LimitReader) Clean() {
r.limiter = nil
}