-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratelimit.go
More file actions
52 lines (43 loc) · 1.15 KB
/
ratelimit.go
File metadata and controls
52 lines (43 loc) · 1.15 KB
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
package csfloat
import (
"net/http"
"strconv"
"time"
)
type Ratelimits struct {
Limit uint
Remaining uint
Reset time.Time
SuggestedWait time.Time
}
// ratelimitsFrom parses the headers to get ratelimiting. It does NOT consume
// the body.
func ratelimitsFrom(response *http.Response) (Ratelimits, error) {
var ratelimits Ratelimits
remaining := response.Header.Get("X-Ratelimit-Remaining")
limit := response.Header.Get("X-Ratelimit-Limit")
reset := response.Header.Get("X-Ratelimit-Reset")
now := time.Now()
remainingInt, err := strconv.ParseUint(remaining, 10, 64)
if err != nil {
return ratelimits, err
}
limitInt, err := strconv.ParseUint(limit, 10, 64)
if err != nil {
return ratelimits, err
}
resetInt, err := strconv.Atoi(reset)
if err != nil {
return ratelimits, err
}
ratelimits.Remaining = uint(remainingInt)
ratelimits.Limit = uint(limitInt)
resetTime := time.Unix(int64(resetInt), 0)
ratelimits.Reset = resetTime
if remainingInt == 0 {
ratelimits.SuggestedWait = resetTime
} else {
ratelimits.SuggestedWait = now.Add(resetTime.Sub(now) / time.Duration(remainingInt))
}
return ratelimits, nil
}