Created
January 15, 2021 00:43
-
-
Save pedrobertao/b49fbcbab55db22fefb93a58c2fe1e29 to your computer and use it in GitHub Desktop.
Function retrier using closure
This file contains 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
/* | |
Retry function using closure | |
*/ | |
package main | |
import ( | |
"errors" | |
"fmt" | |
"time" | |
) | |
type Person struct { | |
name string | |
surname string | |
} | |
func fetchPerson(n string) (Person, error) { | |
time.Sleep(1 * time.Second) | |
if n == "Pedro" { | |
return Person{"Pedro", "Bertao"}, nil | |
} | |
return Person{}, errors.New("Person not found") | |
} | |
func retry(f func() error, numRetries int) (e error) { | |
for i := 0; i < numRetries; i++ { | |
fmt.Printf("Trying %d\n", i+1) | |
if e = f(); e != nil { | |
continue | |
} else { | |
return | |
} | |
} | |
return errors.New("Max retries attemped") | |
} | |
func main() { | |
// Case 1 - Person found | |
var p Person | |
err := retry(func() error { | |
psr, err := fetchPerson("Pedro") | |
p = psr | |
return err | |
}, 5) | |
fmt.Printf("Person found: %+v with err: %v\n", p, err) | |
// Person found: {name:Pedro surname:Bertao} with err: <nil> | |
// Case 2 - Person not found | |
var p2 Person | |
err = retry(func() error { | |
psr, err := fetchPerson("Roberto") | |
p2 = psr | |
return err | |
}, 5) | |
if err != nil { | |
fmt.Printf("Person not found: %+v with err: %v\n", p2, err) | |
// Person not found: {name: surname:} with err: Max retris attemped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment