-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
64 lines (58 loc) · 1.25 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
package asyncretry_test
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
asyncretry "github.com/Kyash/async-retry"
)
func ExampleAsyncRetry() {
mux := http.NewServeMux()
asyncRetry := asyncretry.NewAsyncRetry()
mux.HandleFunc(
"/hello",
func(w http.ResponseWriter, r *http.Request) {
var ctx = r.Context()
if err := asyncRetry.Do(
ctx,
func(ctx context.Context) error {
// do task
// ...
return nil
},
func(err error) {
if err != nil {
log.Println(err.Error())
}
},
asyncretry.Attempts(5),
asyncretry.Timeout(8*time.Second),
); err != nil {
// asyncRetry is in shutdown
log.Println(err.Error())
}
fmt.Fprintf(w, "Hello")
},
)
srv := &http.Server{Handler: mux}
ch := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
if err := srv.Shutdown(context.Background()); err != nil {
log.Printf("HTTP server Shutdown: %v", err)
}
if err := asyncRetry.Shutdown(context.Background()); err != nil {
log.Printf("AsyncRetry Shutdown: %v", err)
}
close(ch)
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("HTTP server ListenAndServe: %v", err)
}
<-ch
}