Last active
March 19, 2023 03:29
-
-
Save nstogner/6e2e37c2f90dd04cae926ebb1c022f78 to your computer and use it in GitHub Desktop.
Go: Simple retry function (HTTP request)
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
// DeleteThing attempts to delete a thing. It will try a maximum of three times. | |
func DeleteThing(id string) error { | |
// Build the request | |
req, err := http.NewRequest( | |
"DELETE", | |
fmt.Sprintf("https://unreliable-api/things/%s", id), | |
nil, | |
) | |
if err != nil { | |
return fmt.Errorf("unable to make request: %s", err) | |
} | |
// Execute the request | |
return retry(3, time.Second, func() error { | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
// This error will result in a retry | |
return err | |
} | |
defer resp.Body.Close() | |
s := resp.StatusCode | |
switch { | |
case s >= 500: | |
// Retry | |
return fmt.Errorf("server error: %v", s) | |
case s >= 400: | |
// Don't retry, it was client's fault | |
return stop{fmt.Errorf("client error: %v", s)} | |
default: | |
// Happy | |
return nil | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment