Last active
April 13, 2022 09:14
-
-
Save sazid/29bfd4b4f9976a0ffb09ca827db391d8 to your computer and use it in GitHub Desktop.
A small generic function for retrying in go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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