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 ( import (
"errors" "errors"
"net/http"
"strconv" "strconv"
"time" "time"
@ -40,17 +41,29 @@ type Client struct {
} }
func NewClient(token string) Client { func NewClient(token string) Client {
resty := resty.New() client := resty.New()
resty.SetBaseURL(listenBrainzBaseURL) client.SetBaseURL(listenBrainzBaseURL)
resty.SetAuthScheme("Token") client.SetAuthScheme("Token")
resty.SetAuthToken(token) client.SetAuthToken(token)
resty.SetHeader("Accept", "application/json") client.SetHeader("Accept", "application/json")
client := Client{
HttpClient: resty, // 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, MaxResults: DefaultItemsPerGet,
} }
return client
} }
func (c Client) GetListens(user string, maxTime time.Time, minTime time.Time) (result GetListensResult, err error) { func (c Client) GetListens(user string, maxTime time.Time, minTime time.Time) (result GetListensResult, err error) {