Last active
January 17, 2023 06:48
-
-
Save nstogner/6ee6c3feb97f5e8360cfe38c75f4acf8 to your computer and use it in GitHub Desktop.
Go: Simple retry function
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, fn func() error) error { | |
if err := fn(); err != nil { | |
if s, ok := err.(stop); ok { | |
// Return the original error for later checking | |
return s.error | |
} | |
if attempts--; attempts > 0 { | |
time.Sleep(sleep) | |
return retry(attempts, 2*sleep, fn) | |
} | |
return err | |
} | |
return nil | |
} | |
type stop struct { | |
error | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good point! I like that version as well... However, the
if err != nil
with a bottomreturn nil
is a such a pattern in the Go world, theif err == nil
sometimes throws me off when reading code.