Created
March 6, 2022 12:15
-
-
Save MaikelVeen/ca499f80bb0e45088411176d7a676362 to your computer and use it in GitHub Desktop.
The Retry Pattern in Go
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
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