Debian Codegraph @

example_test.go

raw
1 package backoff_test
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log"
8 "net/http"
9 "strconv"
10
11 "github.com/cenkalti/backoff/v5"
12 )
13
14 func ExampleRetry() {
15 // Define an operation function that returns a value and an error.
16 // The value can be any type.
17 // We'll pass this operation to Retry function.
18 operation := func() (string, error) {
19 // An example request that may fail.
20 resp, err := http.Get("http://httpbin.org/get")
21 if err != nil {
22 return "", err
23 }
24 defer resp.Body.Close()
25
26 // In case on non-retriable error, return Permanent error to stop retrying.
27 // For this HTTP example, client errors are non-retriable.
28 if resp.StatusCode == 400 {
29 return "", backoff.Permanent(errors.New("bad request"))
30 }
31
32 // If we are being rate limited, return a RetryAfter to specify how long to wait.
33 // This will also reset the backoff policy.
34 if resp.StatusCode == 429 {
35 seconds, err := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64)
36 if err == nil {
37 return "", backoff.RetryAfter(int(seconds))
38 }
39 }
40
41 // Return successful response.
42 return "hello", nil
43 }
44
45 result, err := backoff.Retry(context.TODO(), operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
46 if err != nil {
47 fmt.Println("Error:", err)
48 return
49 }
50
51 // Operation is successful.
52
53 fmt.Println(result)
54 // Output: hello
55 }
56
57 func ExampleTicker() {
58 // An operation that may fail.
59 operation := func() (string, error) {
60 return "hello", nil
61 }
62
63 ticker := backoff.NewTicker(backoff.NewExponentialBackOff())
64 defer ticker.Stop()
65
66 var result string
67 var err error
68
69 // Ticks will continue to arrive when the previous operation is still running,
70 // so operations that take a while to fail could run in quick succession.
71 for range ticker.C {
72 if result, err = operation(); err != nil {
73 log.Println(err, "will retry...")
74 continue
75 }
76
77 break
78 }
79
80 if err != nil {
81 // Operation has failed.
82 fmt.Println("Error:", err)
83 return
84 }
85
86 // Operation is successful.
87
88 fmt.Println(result)
89 // Output: hello
90 }