Skip to content

Commit

Permalink
WIP RoundTripWithRetryBackoff transport
Browse files Browse the repository at this point in the history
  • Loading branch information
mars committed Oct 23, 2018
1 parent da4a536 commit 176c52c
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions v3/round_trip_with_retry_backoff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package heroku

import (
"fmt"
"net/http"

"github.com/cenkalti/backoff"
)

func RoundTripWithRetryBackoff(req *http.Request) (*http.Response, error) {
var lastResponse *http.Response
var lastError error

retryableRoundTrip := func() error {
lastResponse, lastError = http.DefaultTransport.RoundTrip(req)
// Detect Heroku API rate limiting
// https://devcenter.heroku.com/articles/platform-api-reference#client-error-responses
if lastResponse.StatusCode == 429 {
return fmt.Errorf("Heroku API rate limited: 429 Too Many Requests")
}
return nil
}

err := backoff.Retry(retryableRoundTrip, backoff.NewExponentialBackOff())
// Propagate the rate limit error when retries eventually fail.
if err != nil {
if lastResponse != nil {
lastResponse.Body.Close()
}
return nil, err
}
// Propagate all other response errors.
if lastError != nil {
if lastResponse != nil {
lastResponse.Body.Close()
}
return nil, lastError
}

return lastResponse, nil
}

0 comments on commit 176c52c

Please sign in to comment.