-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
example_test.go
71 lines (59 loc) · 1.4 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
// +build go1.13 integration
package breaker_test
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"syscall"
"time"
. "github.com/kamilsk/breaker"
)
func Example_httpRequest() {
const url = "http://example.com/"
example := make(chan struct{})
close(example)
breaker := Multiplex(
BreakByChannel(example),
BreakBySignal(os.Interrupt, syscall.SIGINT, syscall.SIGTERM),
BreakByTimeout(time.Hour),
)
defer breaker.Close()
req, err := http.NewRequestWithContext(ToContext(breaker), http.MethodGet, url, nil)
if err != nil {
panic(err)
}
//nolint:bodyclose
if _, err := http.DefaultClient.Do(req); errors.Is(err, context.Canceled) && errors.Is(breaker.Err(), Interrupted) {
fmt.Println("works well")
}
// output: works well
}
func Example_gracefulShutdown() {
example := make(chan struct{})
breaker := Multiplex(
BreakBySignal(os.Interrupt, syscall.SIGINT, syscall.SIGTERM),
BreakByTimeout(200*time.Millisecond),
)
defer breaker.Close()
server := http.Server{
Addr: "127.0.0.1:",
BaseContext: func(net.Listener) context.Context {
return ToContext(breaker)
},
}
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
close(example)
}()
<-breaker.Done()
if err := server.Shutdown(context.TODO()); err == nil && errors.Is(breaker.Err(), Interrupted) {
fmt.Println("works well")
}
<-example
// output: works well
}