File: example_test.go

package info (click to toggle)
golang-gopkg-retry.v1 0.0~git20161025.0.c09f6b8-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 132 kB
  • ctags: 100
  • sloc: makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,269 bytes parent folder | download | duplicates (3)
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
package retry_test // import "gopkg.in/retry.v1"

import (
	"net/http"
	"time"

	"gopkg.in/retry.v1"
)

func doSomething() (int, error) { return 0, nil }

func shouldRetry(error) bool { return false }

func doSomethingWith(int) {}

func ExampleAttempt_More() {
	// This example shows how Attempt.More can be used to help
	// structure an attempt loop. If the godoc example code allowed
	// us to make the example return an error, we would uncomment
	// the commented return statements.
	attempts := retry.Regular{
		Total: 1 * time.Second,
		Delay: 250 * time.Millisecond,
	}
	for attempt := attempts.Start(nil); attempt.Next(); {
		x, err := doSomething()
		if shouldRetry(err) && attempt.More() {
			continue
		}
		if err != nil {
			// return err
			return
		}
		doSomethingWith(x)
	}
	// return ErrTimedOut
	return
}

func ExampleExponential() {
	// This example shows a retry loop that will retry an
	// HTTP POST request with an exponential backoff
	// for up to 30s.
	strategy := retry.LimitTime(30*time.Second,
		retry.Exponential{
			Initial: 10 * time.Millisecond,
			Factor:  1.5,
		},
	)
	for a := retry.Start(strategy, nil); a.Next(); {
		if reply, err := http.Post("http://example.com/form", "", nil); err == nil {
			reply.Body.Close()
			break
		}
	}
}