Skip to content

Instantly share code, notes, and snippets.

@nstogner
Last active January 17, 2023 06:48
Show Gist options
  • Save nstogner/6ee6c3feb97f5e8360cfe38c75f4acf8 to your computer and use it in GitHub Desktop.
Save nstogner/6ee6c3feb97f5e8360cfe38c75f4acf8 to your computer and use it in GitHub Desktop.
Go: Simple retry function
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
}
@meehow
Copy link

meehow commented Jun 1, 2017

After coding few years in node.js, I have indent allergy.
I would rather write something like:

func retry(attempts int, sleep time.Duration, fn func() error) error {
	err := fn()
	if err == nil {
		return 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
}

@nstogner
Copy link
Author

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.

@nstogner
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment