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