-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (76 loc) · 1.97 KB
/
main.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
package contexts
import (
"context"
"errors"
"fmt"
"time"
)
// Contexts are useful for handling and controlling cancellation
// They also allow carrying request-scoped value across boundaries
// Note: CancelFuncs should always be closed to avoid leakages.
func Run() {
// cancelling because of a deadline.
if err := deadlineCancellation(); err != nil {
fmt.Println("Received a deadline error: ", err.Error())
}
// cancelling because of a direct cancel
if err := contextCancel(); err != nil {
fmt.Println("Received an explicit context cancel: ", err.Error())
}
// cancelling because of a timeout
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if err := contextTimeout(ctx); err != nil {
fmt.Println("Received a cancellation error: ", err.Error())
}
}
func deadlineCancellation() error {
ctx, cancel := context.WithDeadlineCause(context.Background(), time.Now().Add(3*time.Second), errors.New("Deadline exceeded!"))
defer cancel()
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
fmt.Println("No context deadline yet, will keep doing IO")
time.Sleep(time.Second)
}
}
}
func contextTimeout(ctx context.Context) error {
// Block the channel with a simple goro.
neverReady := make(chan struct{})
select {
case <-neverReady:
//
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func contextCancel() error {
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(2 * time.Second)
// force cancel!
cancel()
}()
select {
case <-ctx.Done():
return ctx.Err()
}
}
// Do not store contexts for reuse in a struct
type DoNotDoThis struct {
ctx context.Context
}
// Users have no control/scope to handle deadlines etc.
func (d *DoNotDoThis) Fetch() {
fmt.Println("Performing some IO bound fetch.")
}
// Improved Version:
type DoThis struct {
}
func (d *DoThis) Fetch(ctx context.Context) {
fmt.Println("Performing some IO bound fetch, but its independently cancellable etc.")
}