|
1 | 1 | package webexteams
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "net/http" |
4 | 7 | "os"
|
| 8 | + "strconv" |
| 9 | + "time" |
5 | 10 |
|
6 | 11 | "github.com/go-resty/resty/v2"
|
7 | 12 | )
|
@@ -35,14 +40,46 @@ type Client struct {
|
35 | 40 | }
|
36 | 41 |
|
37 | 42 | type service struct {
|
38 |
| - client *resty.Client |
| 43 | + client *resty.Client |
| 44 | + retryOnTooManyRequests bool |
39 | 45 | }
|
40 | 46 |
|
41 | 47 | // SetAuthToken defines the Authorization token sent in the request
|
42 | 48 | func (s *Client) SetAuthToken(accessToken string) {
|
43 | 49 | s.common.client.SetAuthToken(accessToken)
|
44 | 50 | }
|
45 | 51 |
|
| 52 | +func (s *Client) AddRetryOnTooManyRequestsStatus() { |
| 53 | + if s.common.retryOnTooManyRequests { |
| 54 | + return |
| 55 | + } |
| 56 | + s.common.client.SetRetryCount(3) |
| 57 | + s.common.client.SetRetryAfter( |
| 58 | + func(c *resty.Client, r *resty.Response) (time.Duration, error) { |
| 59 | + // Retrying but not on a 429, we retry immediately |
| 60 | + if r.StatusCode() != http.StatusTooManyRequests { |
| 61 | + return time.Duration(0), nil |
| 62 | + } |
| 63 | + retryAfterRaw := r.Header().Get("Retry-After") |
| 64 | + if retryAfterRaw == "" { |
| 65 | + return 0, errors.New("received a 429, but got an empty Retry-After header") |
| 66 | + } |
| 67 | + retryAfter, err := strconv.Atoi(retryAfterRaw) |
| 68 | + if err != nil { |
| 69 | + return 0, fmt.Errorf("invalid Retry-After header: %v", retryAfterRaw) |
| 70 | + } |
| 71 | + fmt.Println(time.Second * time.Duration(retryAfter)) |
| 72 | + return time.Second * time.Duration(retryAfter), nil |
| 73 | + }, |
| 74 | + ) |
| 75 | + s.common.client.AddRetryCondition( |
| 76 | + func(r *resty.Response, err error) bool { |
| 77 | + return r.StatusCode() == http.StatusTooManyRequests |
| 78 | + }, |
| 79 | + ) |
| 80 | + s.common.retryOnTooManyRequests = true |
| 81 | +} |
| 82 | + |
46 | 83 | // NewClient creates a new API client. Requires a userAgent string describing your application.
|
47 | 84 | // optionally a custom http.Client to allow for advanced features such as caching.
|
48 | 85 | func NewClient() *Client {
|
|
0 commit comments