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 (
|
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) {
|
||||||
|
|
Loading…
Add table
Reference in a new issue