Skip to content

Instantly share code, notes, and snippets.

@MaikelVeen
Created March 6, 2022 12:15
Show Gist options
  • Save MaikelVeen/ca499f80bb0e45088411176d7a676362 to your computer and use it in GitHub Desktop.
Save MaikelVeen/ca499f80bb0e45088411176d7a676362 to your computer and use it in GitHub Desktop.
The Retry Pattern in Go
type Effector func(context.Context) (string, error)
func Retry(effector Effector, retries int, delay time.Duration) Effector {
return func(ctx context.Context) (string, 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.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