Skip to content

Instantly share code, notes, and snippets.

@diegostamigni
Created November 2, 2022 15:09
Show Gist options
  • Save diegostamigni/2fed44bd72e3e2c44ed9391f8e4e7a0c to your computer and use it in GitHub Desktop.
Save diegostamigni/2fed44bd72e3e2c44ed9391f8e4e7a0c to your computer and use it in GitHub Desktop.
Golang generic retry
func Retry[T any](effector func(ctx context.Context) (T, error), retries int, delay time.Duration) func(context.Context) (*T, error) {
return func(ctx context.Context) (*T, error) {
for r := 0; ; r++ {
response, err := effector(ctx)
if err == nil || r >= retries {
// Return when there is no error or the maximum amount
// of retries is reached.
return &response, err
}
log.Println("Function call failed, retrying in", delay)
select {
case <-time.After(delay):
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
}
@diegostamigni
Copy link
Author

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