Skip to content

Commit 3ef1b60

Browse files
authored
Comply with rate limit (#18)
1 parent 259bddb commit 3ef1b60

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

_deploy/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func main() {
4444
must(err)
4545

4646
// Connect to zendesk
47-
transport := BasicAuthTransport{
47+
transport := ZendeskAuthTransport{
4848
Username: Config.ZendeskUser + "/token",
4949
Password: Config.ZendeskToken,
5050
}

_deploy/zendesk.go

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"os"
1212
"path/filepath"
13+
"strconv"
1314
"time"
1415
)
1516

@@ -440,17 +441,27 @@ func (z *Zendesk) DeleteAttachment(attachmentID int) (err error) {
440441
return nil
441442
}
442443

443-
type BasicAuthTransport struct {
444+
type ZendeskAuthTransport struct {
444445
Username string
445446
Password string
446447
}
447448

448-
func (bat BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
449-
req.SetBasicAuth(bat.Username, bat.Password)
449+
func (z ZendeskAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
450+
req.SetBasicAuth(z.Username, z.Password)
450451

451-
return http.DefaultTransport.RoundTrip(req)
452+
res, err := http.DefaultTransport.RoundTrip(req)
453+
if res.StatusCode == 429 {
454+
// we hit the rate limit, wait for the suggested seconds and retry
455+
if waitFor, castErr := strconv.Atoi(res.Header.Get("Retry-After")); castErr == nil {
456+
Log.Warnf("Rate limited: wait for %d seconds", waitFor)
457+
458+
time.Sleep(time.Duration(waitFor) * time.Second)
459+
return http.DefaultTransport.RoundTrip(req)
460+
}
461+
}
462+
return res, err
452463
}
453464

454-
func (bat *BasicAuthTransport) Client() *http.Client {
455-
return &http.Client{Transport: bat}
465+
func (z *ZendeskAuthTransport) Client() *http.Client {
466+
return &http.Client{Transport: z}
456467
}

0 commit comments

Comments
 (0)