mirror of
https://git.sr.ht/~phw/scotty
synced 2025-04-16 10:09:28 +02:00
Spotify: consider rate limit HTTP headers
This commit is contained in:
parent
68b2e649f0
commit
780af98e1e
1 changed files with 20 additions and 0 deletions
|
@ -25,6 +25,7 @@ package spotify
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -34,6 +35,7 @@ import (
|
||||||
|
|
||||||
const baseURL = "https://api.spotify.com/v1/"
|
const baseURL = "https://api.spotify.com/v1/"
|
||||||
const MaxItemsPerGet = 50
|
const MaxItemsPerGet = 50
|
||||||
|
const DefaultRateLimitWaitSeconds = 5
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
HttpClient *resty.Client
|
HttpClient *resty.Client
|
||||||
|
@ -46,6 +48,24 @@ func NewClient(token oauth2.TokenSource) Client {
|
||||||
client.SetBaseURL(baseURL)
|
client.SetBaseURL(baseURL)
|
||||||
client.SetHeader("Accept", "application/json")
|
client.SetHeader("Accept", "application/json")
|
||||||
client.SetRetryCount(5)
|
client.SetRetryCount(5)
|
||||||
|
client.AddRetryCondition(
|
||||||
|
func(r *resty.Response, err error) bool {
|
||||||
|
code := r.StatusCode()
|
||||||
|
return code == http.StatusTooManyRequests || code >= http.StatusInternalServerError
|
||||||
|
},
|
||||||
|
)
|
||||||
|
client.SetRetryMaxWaitTime(time.Duration(1 * time.Minute))
|
||||||
|
client.SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
|
||||||
|
var err error
|
||||||
|
var retryAfter int = DefaultRateLimitWaitSeconds
|
||||||
|
if resp.StatusCode() == http.StatusTooManyRequests {
|
||||||
|
retryAfter, err = strconv.Atoi(resp.Header().Get("Retry-After"))
|
||||||
|
if err != nil {
|
||||||
|
retryAfter = DefaultRateLimitWaitSeconds
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return time.Duration(retryAfter * int(time.Second)), err
|
||||||
|
})
|
||||||
return Client{
|
return Client{
|
||||||
HttpClient: client,
|
HttpClient: client,
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue