retry

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package retry provides functionality to retry operations with configurable attempts and backoff.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DoWithResult

func DoWithResult[T any](r *Retry, fn func() (T, error)) (T, error)

DoWithResult executes the given function with configured retry behavior and returns a result. Works like Do() but for functions that return a value along with an error. On failure, returns the result from the last attempt along with the final error.

Example:

r := retry.New(retry.Attempts(3))
user, err := retry.DoWithResult(r, func() (*User, error) {
	return fetchUserFromAPI(userID)
})
if err != nil {
	log.Printf("failed to fetch user after 3 attempts: %v", err)
}

func DoWithResultContext

func DoWithResultContext[T any](r *Retry, ctx context.Context, fn func() (T, error)) (T, error)

DoWithResultContext executes the given function with configured retry behavior, context support, and returns a result. Works like DoContext() but for functions that return a value along with an error. On failure, returns the result from the last attempt along with the final error.

Types

type Apply

type Apply func(r *Retry) *Retry

Apply modifies r and returns it

func Attempts

func Attempts(attempts int) Apply

Attempts sets the maximum number of retry attempts. The operation will be attempted up to this many times before giving up.

func Backoff

func Backoff(backoff func(n int) time.Duration) Apply

Backoff sets the backoff strategy function. The function receives the current attempt number (starting with 1) and should return the duration to wait before the next attempt.

func ShouldRetry

func ShouldRetry(shouldRetry func(error) bool) Apply

ShouldRetry sets a function to determine if an error should trigger a retry. If not set or set to nil, all errors will trigger retries. This is useful for skipping retries on non-transient errors like "not found".

Example:

r := retry.New(
	retry.Attempts(3),
	retry.ShouldRetry(func(err error) bool {
		// Don't retry if the error is a "not found" error
		if errors.Is(err, ErrNotFound) {
			return false
		}
		// Retry all other errors
		return true
	}),
)

type Retry

type Retry struct {
	// contains filtered or unexported fields
}

Retry holds the configuration for retry attempts and backoff strategy.

func New

func New(applies ...Apply) *Retry

New creates a new retry instance with default configuration. Default configuration:

  • 3 retry attempts
  • Linear backoff starting at 100ms, increasing by 100ms per attempt

Example:

r := retry.New()
err := r.Do(func() error {
	// Simulate an operation that might fail
	resp, err := http.Get("https://api.example.com")
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status: %d", resp.StatusCode)
	}
	return nil
})

if err != nil {
	log.Printf("operation failed after 3 attempts: %v", err)
}

The retry behavior can be customized using Attempts() and Backoff():

r := retry.New(

retry.Attempts(5),
retry.Backoff(func(n int) time.Duration {
	return time.Duration(1<<uint(n)) * time.Second // exponential backoff
}),

)

func (*Retry) Do

func (r *Retry) Do(fn func() error) error

Do executes the given function with configured retry behavior. The function is retried until it succeeds or the maximum number of attempts is reached. Between attempts, the backoff function determines the wait duration. If shouldRetry is configured, it will be called to determine if a retry should occur.

Returns nil if the operation succeeds, or the last error encountered if all retries fail or if the error is non-retryable according to shouldRetry. Returns an error if attempts is configured to less than 1.

func (*Retry) DoContext

func (r *Retry) DoContext(ctx context.Context, fn func() error) error

DoContext executes the given function with configured retry behavior while respecting context cancellation and deadlines. The function is retried until it succeeds, the maximum number of attempts is reached, or the context is cancelled/expired.

Context awareness:

  • Checks context before each attempt and returns immediately if cancelled or deadline exceeded
  • Uses select during backoff sleep to detect context cancellation without waiting for full sleep duration
  • Returns context.Canceled if context was cancelled, or context.DeadlineExceeded if deadline passed

Returns nil if the operation succeeds, the context error if context is done, or the last error encountered if all retries fail or if the error is non-retryable according to shouldRetry. Returns an error if attempts is configured to less than 1.

Example:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

r := retry.New(retry.Attempts(3))
err := r.DoContext(ctx, func() error {
	return someNetworkCall()
})

Jump to

Keyboard shortcuts

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