zdravko/pkg/retry/retry.go

24 lines
508 B
Go
Raw Normal View History

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)
}