...
Source file
src/context/example_test.go
Documentation: context
1
2
3
4
5 package context_test
6
7 import (
8 "context"
9 "fmt"
10 "time"
11 )
12
13 const shortDuration = 1 * time.Millisecond
14
15
16
17
18 func ExampleWithCancel() {
19
20
21
22
23
24 gen := func(ctx context.Context) <-chan int {
25 dst := make(chan int)
26 n := 1
27 go func() {
28 for {
29 select {
30 case <-ctx.Done():
31 return
32 case dst <- n:
33 n++
34 }
35 }
36 }()
37 return dst
38 }
39
40 ctx, cancel := context.WithCancel(context.Background())
41 defer cancel()
42
43 for n := range gen(ctx) {
44 fmt.Println(n)
45 if n == 5 {
46 break
47 }
48 }
49
50
51
52
53
54
55 }
56
57
58
59 func ExampleWithDeadline() {
60 d := time.Now().Add(shortDuration)
61 ctx, cancel := context.WithDeadline(context.Background(), d)
62
63
64
65
66 defer cancel()
67
68 select {
69 case <-time.After(1 * time.Second):
70 fmt.Println("overslept")
71 case <-ctx.Done():
72 fmt.Println(ctx.Err())
73 }
74
75
76
77 }
78
79
80
81 func ExampleWithTimeout() {
82
83
84 ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
85 defer cancel()
86
87 select {
88 case <-time.After(1 * time.Second):
89 fmt.Println("overslept")
90 case <-ctx.Done():
91 fmt.Println(ctx.Err())
92 }
93
94
95
96 }
97
98
99
100 func ExampleWithValue() {
101 type favContextKey string
102
103 f := func(ctx context.Context, k favContextKey) {
104 if v := ctx.Value(k); v != nil {
105 fmt.Println("found value:", v)
106 return
107 }
108 fmt.Println("key not found:", k)
109 }
110
111 k := favContextKey("language")
112 ctx := context.WithValue(context.Background(), k, "Go")
113
114 f(ctx, k)
115 f(ctx, favContextKey("color"))
116
117
118
119
120 }
121
View as plain text