ListenBrainz: Handle rate limit

This commit is contained in:
Philipp Wolfer 2023-11-13 09:48:16 +01:00
parent ebcec46d7a
commit 161ada7aff
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B

View file

@ -23,6 +23,7 @@ package listenbrainz
import (
"errors"
"net/http"
"strconv"
"time"
@ -40,17 +41,29 @@ type Client struct {
}
func NewClient(token string) Client {
resty := resty.New()
resty.SetBaseURL(listenBrainzBaseURL)
resty.SetAuthScheme("Token")
resty.SetAuthToken(token)
resty.SetHeader("Accept", "application/json")
client := Client{
HttpClient: resty,
client := resty.New()
client.SetBaseURL(listenBrainzBaseURL)
client.SetAuthScheme("Token")
client.SetAuthToken(token)
client.SetHeader("Accept", "application/json")
// Handle rate limiting (see https://listenbrainz.readthedocs.io/en/latest/users/api/index.html#rate-limiting)
client.SetRetryCount(5)
client.AddRetryCondition(
func(r *resty.Response, err error) bool {
return r.StatusCode() == http.StatusTooManyRequests
},
)
client.SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
resetIn, err := strconv.Atoi(resp.Header().Get("X-RateLimit-Reset-In"))
// fmt.Printf("R %v: %v, %v\n", resp.Request.URL, resetIn, err)
return time.Duration(resetIn * int(time.Second)), err
})
return Client{
HttpClient: client,
MaxResults: DefaultItemsPerGet,
}
return client
}
func (c Client) GetListens(user string, maxTime time.Time, minTime time.Time) (result GetListensResult, err error) {