blob: be622f64c3c31b212f7a361026e04a9757de617a (
plain) (
blame)
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
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package ratelimit
import (
"time"
"github.com/philippta/flyscrape"
)
func init() {
flyscrape.RegisterModule(new(Module))
}
type Module struct {
Rate float64 `json:"rate"`
ticker *time.Ticker
semaphore chan struct{}
}
func (m *Module) OnLoad(v flyscrape.Visitor) {
rate := time.Duration(float64(time.Second) / m.Rate)
m.ticker = time.NewTicker(rate)
m.semaphore = make(chan struct{}, 1)
go func() {
for range m.ticker.C {
m.semaphore <- struct{}{}
}
}()
}
func (m *Module) OnRequest(_ *flyscrape.Request) {
<-m.semaphore
}
func (m *Module) OnComplete() {
m.ticker.Stop()
}
var (
_ flyscrape.OnRequest = (*Module)(nil)
_ flyscrape.OnLoad = (*Module)(nil)
_ flyscrape.OnComplete = (*Module)(nil)
)
|