Skip to content

Instantly share code, notes, and snippets.

@donchev7
Created August 14, 2022 15:40
Show Gist options
  • Save donchev7/c910e19472684eb2b16062fbbba9d93d to your computer and use it in GitHub Desktop.
Save donchev7/c910e19472684eb2b16062fbbba9d93d to your computer and use it in GitHub Desktop.
Go retry function
type Action func(context.Context) (string, error)
func Retry(action Action, retries int, delay time.Duration) Action {
return func(ctx context.Context) (string, error) {
for r := 0; ; r++ {
response, err := action(ctx)
if err == nil || r >= retries {
// Return when there is no error or the maximum amount
// of retries is reached.
return response, err
}
log.Printf("Function call failed, retrying in %v", delay)
select {
case <-time.After(delay):
case <-ctx.Done():
return "", ctx.Err()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment