Created
August 14, 2022 15:40
-
-
Save donchev7/c910e19472684eb2b16062fbbba9d93d to your computer and use it in GitHub Desktop.
Go retry function
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
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