Last active
July 31, 2017 18:43
-
-
Save jacoelho/200e7ea996d130a54fedae02496d3e7f to your computer and use it in GitHub Desktop.
naive retry golang
This file contains hidden or 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
// Retry - http client with retry support | |
type Retry struct { | |
http.RoundTripper | |
} | |
// Naive Retry - every 2 seconds | |
func (r *Retry) RoundTrip(req *http.Request) (*http.Response, error) { | |
for { | |
resp, err := r.RoundTripper.RoundTrip(req) | |
if err == nil && resp.StatusCode < 500 { | |
return resp, err | |
} | |
select { | |
// check if canceled or timed-out | |
case <-req.Context().Done(): | |
return resp, req.Context().Err() | |
case <-time.After(2 * time.Second): | |
} | |
} | |
} | |
func main() { | |
c := &http.Client{ | |
Transport: &Retry{http.DefaultTransport}, | |
} | |
req, err := http.NewRequest("GET", "https://www.google.com", nil) | |
if err != nil { | |
log.Fatalf("Could not create request") | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
defer cancel() | |
req = req.WithContext(ctx) | |
resp, err := c.Do(req) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer resp.Body.Close() | |
log.Println(resp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment