Spotify: consider rate limit HTTP headers

This commit is contained in:
Philipp Wolfer 2023-11-23 10:49:40 +01:00
parent 68b2e649f0
commit 780af98e1e
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B

View file

@ -25,6 +25,7 @@ package spotify
import (
"context"
"errors"
"net/http"
"strconv"
"time"
@ -34,6 +35,7 @@ import (
const baseURL = "https://api.spotify.com/v1/"
const MaxItemsPerGet = 50
const DefaultRateLimitWaitSeconds = 5
type Client struct {
HttpClient *resty.Client
@ -46,6 +48,24 @@ func NewClient(token oauth2.TokenSource) Client {
client.SetBaseURL(baseURL)
client.SetHeader("Accept", "application/json")
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{
HttpClient: client,
}