retry

package
v3.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2022 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package retry allows to use retry mechanism (call some function until it does not return non-error result or attempts count is not exceeded).

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrToManyAttempts = errors.New("too many attempts") // Too many retry attempts exceeded.
	ErrNoAttempts     = errors.New("no attempts")       // No retry attempts.
	ErrRetryStopped   = errors.New("retry attempts was stopped")
)

Functions

func Do

func Do(fn func(attemptNum uint) error, options ...Option) error

Do executes passed function and repeat it until non-error returned or maximum retries attempts count in not exceeded. Attempts counter starts from 1.

Example
var (
	content []byte
	ctx     = context.Background()
)

err := Do(func(uint) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpbin.org/anything", nil)
	if err != nil {
		return err
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer func() { _ = resp.Body.Close() }()

	content, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	return nil
}, WithContext(ctx), WithAttempts(10), WithDelay(time.Second), WithLastErrorReturning())

if err != nil {
	panic(err)
}

fmt.Printf("Response: %s", string(content))
Output:

Types

type Option

type Option func(*config)

func WithAttempts

func WithAttempts(attempts uint) Option

WithAttempts overrides default attempts count.

func WithContext

func WithContext(ctx context.Context) Option

WithContext overrides default context (by default `context.Background()` is used).

func WithDelay

func WithDelay(delay time.Duration) Option

WithDelay overrides default retry delay.

func WithLastErrorReturning

func WithLastErrorReturning() Option

WithLastErrorReturning allows to return last execution error (instead ErrToManyAttempts or context error).

func WithRetryStoppingErrors

func WithRetryStoppingErrors(e ...error) Option

WithRetryStoppingErrors allows to thor the retry loop when defined error returned from calling function.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL