retry

package
v4.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2023 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

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

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

The default attempts count is 3 (without delay between attempts).

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"

	"gh.tarampamp.am/tinifier/v4/internal/retry"
)

func main() {
	var ctx = context.Background()

	limitExceeded, err := retry.Do(func(attemptNum uint) error {
		fmt.Println(attemptNum) // the function accepts attempt number as an argument

		// some unstable function call should be here. for example - calling the remote API, or something else
		if attemptNum < 3 {
			return errors.New("foo error")
		}

		fmt.Println("success")

		return nil // you should return nil if retrying is not needed
	}, retry.WithContext(ctx), retry.Attempts(10), retry.Delay(time.Millisecond*10))

	if err != nil {
		panic(err)
	}

	fmt.Println("Limit exceeded:", limitExceeded)

}
Output:

1
2
3
success
Limit exceeded: false

Types

type Option

type Option func(*config)

func Attempts

func Attempts(attempts uint) Option

Attempts sets the maximum allowed retries count (set 0 to disable the limitation at all).

func Delay

func Delay(delay time.Duration) Option

Delay overrides default retry delay.

func StopOnError

func StopOnError(e ...error) Option

StopOnError allows stopping the retry loop when one of the defined errors returned from the calling function.

func WithContext

func WithContext(ctx context.Context) Option

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

Jump to

Keyboard shortcuts

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