mirror of
https://git.sr.ht/~phw/scotty
synced 2025-04-16 10:09:28 +02:00
ListenBrainz: Handle rate limit
This commit is contained in:
parent
ebcec46d7a
commit
161ada7aff
1 changed files with 22 additions and 9 deletions
|
@ -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) {
|
||||
|
|
Loading…
Add table
Reference in a new issue