mirror of
https://github.com/mentos1386/zdravko.git
synced 2024-11-27 01:33:37 +00:00
24 lines
508 B
Go
24 lines
508 B
Go
|
package retry
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
// https://stackoverflow.com/questions/67069723/keep-retrying-a-function-in-golang
|
||
|
func Retry[T any](attempts int, sleep time.Duration, f func() (T, error)) (result T, err error) {
|
||
|
for i := 0; i < attempts; i++ {
|
||
|
if i > 0 {
|
||
|
log.Println("retrying after error:", err)
|
||
|
time.Sleep(sleep)
|
||
|
sleep *= 2
|
||
|
}
|
||
|
result, err = f()
|
||
|
if err == nil {
|
||
|
return result, nil
|
||
|
}
|
||
|
}
|
||
|
return result, fmt.Errorf("after %d attempts, last error: %s", attempts, err)
|
||
|
}
|