Skip to content

Instantly share code, notes, and snippets.

@sazid
Last active April 13, 2022 09:14
Show Gist options
  • Save sazid/29bfd4b4f9976a0ffb09ca827db391d8 to your computer and use it in GitHub Desktop.
Save sazid/29bfd4b4f9976a0ffb09ca827db391d8 to your computer and use it in GitHub Desktop.
A small generic function for retrying in go.
func main() {
db, err := util.Retry(120, time.Second, func() (*pgxpool.Pool, error) {
return pgxpool.Connect(...)
})
if err != nil {
log.Fatal("failed to initialize new postgres db pool")
}
}
package util
import (
"fmt"
"time"
)
// Retry tries to perform an action and retries on error for n times with a wait
// duration in between.
func Retry[T any](n int, wait time.Duration, action func() (*T, error)) (*T, error) {
var result *T
var err error
for i := 0; i < n; i++ {
if result, err = action(); err != nil {
fmt.Printf("attempt #%d, retrying after wait period", i)
time.Sleep(wait)
} else {
break
}
}
if err != nil {
return nil, fmt.Errorf("failed after retrying %d times with error: %w", n, err)
}
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment