-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_test.go
91 lines (76 loc) · 1.72 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
91
package contextio_test
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"time"
"github.com/dolmen-go/contextio"
)
func Example_copy() {
// interrupt context after 500ms
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
// interrupt context with SIGTERM (CTRL+C)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
go func() {
<-sigs
cancel()
}()
fIn, err := os.Open("/dev/zero")
if err != nil {
log.Fatal(err)
}
defer fIn.Close()
fOut, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
log.Fatal(err)
}
defer fOut.Close()
// Reader that fails when context is canceled
in := contextio.NewReader(ctx, fIn)
// Writer that fails when context is canceled
out := contextio.NewWriter(ctx, fOut)
n, err := io.Copy(out, in)
log.Println(n, "bytes copied.")
if err != nil {
fmt.Println("Err:", err)
}
fmt.Println("Closing.")
// Output:
// Err: context deadline exceeded
// Closing.
}
func ExampleNewWriter() {
// interrupt context after 500ms
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
// interrupt context with SIGTERM (CTRL+C)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
go func() {
<-sigs
cancel()
}()
f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Writer that fails when context is canceled
out := contextio.NewWriter(ctx, f)
// Infinite loop. Will only be interrupted once write fails.
for {
if _, err := out.Write([]byte{'a', 'b', 'c'}); err != nil {
fmt.Println("Err:", err)
break
}
}
fmt.Println("Closing.")
// Output:
// Err: context deadline exceeded
// Closing.
}