Created
August 13, 2021 09:30
-
-
Save prnvbn/d4e8765167c90ff4e92b73c86c827422 to your computer and use it in GitHub Desktop.
A retry function in Golang
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
func retry(attempts int, sleep time.Duration, f func() error) (err error) { | |
for i := 0; i < attempts; i++ { | |
if i > 0 { | |
log.Println("retrying after error:", err) | |
time.Sleep(sleep) | |
sleep *= 2 | |
} | |
err = f() | |
if err == nil { | |
return nil | |
} | |
} | |
return fmt.Errorf("after %d attempts, last error: %s", attempts, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment