Documentation ¶
Index ¶
Examples ¶
Constants ¶
const ( DefaultMaxTries = 5 DefaultInitialDelay = time.Millisecond * 200 DefaultMaxDelay = time.Millisecond * 1000 )
Default backoff
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Retrier ¶
type Retrier struct {
// contains filtered or unexported fields
}
Retrier retries code blocks with or without context using an exponential backoff algorithm with jitter. It is intended to be used as a retry policy, which means it is safe to create and use concurrently.
func NewRetrier ¶
NewRetrier returns a retrier for retrying functions with expoential backoff. If any of the values are <= 0, they will be set to their respective defaults.
func (*Retrier) Run ¶
Run runs a function until it returns nil, until it returns a terminal error, or until it has failed the maximum set number of iterations
Example ¶
retrier := NewRetrier(5, 50*time.Millisecond, 50*time.Millisecond) err := retrier.Run(func() error { resp, err := http.Get("http://golang.org") switch { case err != nil: return err case resp.StatusCode == 0 || resp.StatusCode >= 500: return fmt.Errorf("Retryable HTTP status: %s", http.StatusText(resp.StatusCode)) case resp.StatusCode != 200: return Stop(fmt.Errorf("Non-retryable HTTP status: %s", http.StatusText(resp.StatusCode))) } return nil }) fmt.Println(err)
Output:
func (*Retrier) RunContext ¶
RunContext runs a function until it returns nil, until it returns a terminal error, until its context is done, or until it has failed the maximum set number of iterations.
Note: it is the responsibility of the called function to do its part in honoring context deadlines. retry has no special magic around this, and will simply stop the retry loop when the function returns if the context is done.
Example (Output) ¶
retrier := NewRetrier(5, 50*time.Millisecond, 50*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() err := retrier.RunContext(ctx, func(ctx context.Context) error { req, _ := http.NewRequest("GET", "http://golang.org/notfastenough", nil) req = req.WithContext(ctx) resp, err := http.DefaultClient.Do(req) if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf("OMG AWFUL CODE %d", resp.StatusCode) // or decide not to retry } return nil }) fmt.Println(err)
Output: Get "http://golang.org/notfastenough": context deadline exceeded