-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
WIP RoundTripWithRetryBackoff transport
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |