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 | |
} |
Good point! I like that version as well... However, the if err != nil
with a bottom return nil
is a such a pattern in the Go world, the if err == nil
sometimes throws me off when reading code.
Blog post here: https://upgear.io/blog/simple-golang-retry-function/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After coding few years in node.js, I have indent allergy.
I would rather write something like: