Skip to content

Instantly share code, notes, and snippets.

@prnvbn
Created August 13, 2021 09:30
Show Gist options
  • Save prnvbn/d4e8765167c90ff4e92b73c86c827422 to your computer and use it in GitHub Desktop.
Save prnvbn/d4e8765167c90ff4e92b73c86c827422 to your computer and use it in GitHub Desktop.
A retry function in Golang
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