Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/soreing/retrier
Simple and flexible go retrier
https://github.com/soreing/retrier
go golang retry retrying
Last synced: 7 days ago
JSON representation
Simple and flexible go retrier
- Host: GitHub
- URL: https://github.com/soreing/retrier
- Owner: Soreing
- License: mit
- Created: 2022-10-25T16:53:44.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2023-08-23T21:11:15.000Z (about 1 year ago)
- Last Synced: 2024-10-15T02:50:02.304Z (22 days ago)
- Topics: go, golang, retry, retrying
- Language: Go
- Homepage:
- Size: 18.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Retrier
![Build](https://github.com/soreing/retrier/actions/workflows/build_status.yaml/badge.svg)
![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Soreing/4b6f950f01f3e6e5b9ed17b268664538/raw/retrier)
[![Go Report Card](https://goreportcard.com/badge/github.com/Soreing/retrier)](https://goreportcard.com/report/github.com/Soreing/retrier)
[![Go Reference](https://pkg.go.dev/badge/github.com/Soreing/retrier.svg)](https://pkg.go.dev/github.com/Soreing/retrier)Retrier is a small package that makes retrying anything easier with custom or predefined retry functions.
## Usage
Create a retrier by providing an upper limit to retries and a delay function.
```golang
ret := retrier.NewRetrier(
10, // -1 for no limit
retrier.ConstantDelay(time.Second),
)
```
You can use one of the predefined delay functions, or provide your own.
```golang
ret := retrier.NewRetrier(
-1,
func(count int) time.Duration {
m := rand.Intn(60)
return time.Second * time.Duration(m)
},
)
```
Use the Run or RunCtx functions to run any task. The retrier will retry the task if it returns true ("should retry"). The retrier will not retry the task if it returns false ("should not retry"), if the retry cap is reached or if the context is canceled.
```golang
ret.RunCtx(
context.TODO(),
func(ctx context.Context) (error, bool) {
resp, err := http.Get("https://some-api.com")
if err != nil {
fmt.Println("request failed")
return err, true
} else {
fmt.Println(resp)
return nil, false
}
},
)
```
## Delay Functions
| Function | Delay | Example |
|----------|-------|---------|
| No Delay | `0` | 0, 0, 0, 0, 0 |
| Constant Delay | `c` | 1, 1, 1, 1, 1 |
| Linear Delay | `r*c` | 1, 2, 3, 4, 5 |
| Capped Linear Delay | `min(r*c, cap)` | 1, 2, 3, 3, 3 |
| Exponential Delay | `a*b^r` | 2, 4, 8, 16, 32 |
| Capped Exponential Delay | `min(a*b^r, cap)` | 2, 4, 8, 10, 10 |