Skip to content

Commit 31608a7

Browse files
committed
Ⓜ️ Improve rate limiting handling
1 parent 7f978d8 commit 31608a7

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

cmd/utils.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net/http"
88
"reflect"
99
"regexp"
10+
"strconv"
1011
"strings"
1112
"time"
1213

@@ -134,8 +135,17 @@ func makeSimpleAPIRequest(method string, url string, payload io.Reader, expected
134135
}
135136
defer resp.Body.Close()
136137

137-
if resp.StatusCode == 429 {
138-
logger.Printf("Rate limit exceeded, waiting %d second...\n", rateLimitWaitTime)
138+
if resp.StatusCode == http.StatusTooManyRequests {
139+
// Proper way to handle rate limit would be to parse the X-Ratelimit-Reset header
140+
if resetHeaderValue, ok := resp.Header["X-Ratelimit-Reset"]; ok {
141+
if sleep, err := strconv.ParseInt(resetHeaderValue[0], 10, 64); err == nil {
142+
logger.Printf("Rate limit exceeded, waiting %d seconds...\n", sleep)
143+
time.Sleep(time.Duration(sleep) * time.Second)
144+
return makeSimpleAPIRequest(method, url, payload, expectedStatusCode)
145+
}
146+
}
147+
// If the header is not present, we will wait for a fixed time
148+
logger.Printf("Rate limit exceeded, waiting %d seconds...\n", rateLimitWaitTime)
139149
time.Sleep(time.Duration(rateLimitWaitTime) * time.Second)
140150
return makeSimpleAPIRequest(method, url, payload, expectedStatusCode)
141151
}

0 commit comments

Comments
 (0)