Yet another retrier \o/
go get -u github.com/vthiery/retry
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/vthiery/retry"
)
var nonRetryableError = errors.New("a non-retryable error")
func main() {
// Define the retry strategy, with 10 attempts and an exponential backoff
retry := retry.New(
retry.WithMaxAttempts(10),
retry.WithBackoff(
retry.NewExponentialBackoff(
100*time.Millisecond, // minWait
1*time.Second, // maxWait
2*time.Millisecond, // maxJitter
),
),
retry.WithPolicy(
func(err error) bool {
return !errors.Is(err, nonRetryableError)
},
),
)
// A cancellable context can be used to stop earlier
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Define the function that can be retried
operation := func(ctx context.Context) error {
fmt.Println("doing something...")
return errors.New("actually, can't do it 🤦")
}
// Call the `retry.Do` to attempt to perform `fn`
if err := retry.Do(ctx, operation); err != nil {
fmt.Printf("failed to perform `fn`: %v\n", err)
}
}