-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrate_limit.go
47 lines (44 loc) · 975 Bytes
/
rate_limit.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
package osuapi
import (
"time"
)
var every time.Duration
var requestsAvailable chan struct{}
var routStarted bool
// RateLimit allows you to set the maximum number of requests to do in a
// minute to the osu! API.
//
// Please note that this function is NOT thread safe. It should be executed
// only at the start of your program, and never after it.
//
// The reason for this is that creating a Mutex for a channel is just
// absolutely ridiculous.
func RateLimit(maxRequests int) {
if maxRequests == 0 {
requestsAvailable = nil
}
every = 60000 * time.Millisecond / time.Duration(maxRequests)
requestsAvailable = make(chan struct{}, maxRequests)
for {
var b bool
select {
case requestsAvailable <- struct{}{}:
// nothing, just keep on moving
default:
b = true
}
if b {
break
}
}
if !routStarted {
go requestIncreaser()
}
routStarted = true
}
func requestIncreaser() {
for {
time.Sleep(every)
requestsAvailable <- struct{}{}
}
}