Created
November 2, 2022 15:09
-
-
Save diegostamigni/2fed44bd72e3e2c44ed9391f8e4e7a0c to your computer and use it in GitHub Desktop.
Golang generic retry
This file contains hidden or 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
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() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generic solution proposal re https://medium.com/gitconnected/make-your-go-code-more-reliable-with-the-retry-pattern-e9968a2050ba