File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "time"
7
+ )
8
+
9
+ func main () {
10
+ ctx , cancel := context .WithTimeout (context .Background (), time .Second * 4 )
11
+ defer cancel ()
12
+ go fmt .Println (doFuncSuccess (ctx ))
13
+ go fmt .Println (doFuncFail (ctx ))
14
+ time .Sleep (time .Second * 6 )
15
+ fmt .Println ("doFuncFail" )
16
+ go fmt .Println (doFuncFail (ctx ))
17
+ time .Sleep (time .Second * 2 )
18
+ }
19
+
20
+ func doFuncSuccess (ctx context.Context ) string {
21
+ select {
22
+ case <- ctx .Done ():
23
+ return ctx .Err ().Error ()
24
+ default :
25
+ }
26
+ time .Sleep (time .Second * 3 )
27
+ select {
28
+ case <- ctx .Done ():
29
+ return ctx .Err ().Error ()
30
+ default :
31
+ }
32
+ return "success"
33
+ }
34
+
35
+ func doFuncFail (ctx context.Context ) string {
36
+ select {
37
+ case <- ctx .Done ():
38
+ return ctx .Err ().Error ()
39
+ default :
40
+ }
41
+
42
+ time .Sleep (time .Second * 5 )
43
+
44
+ select {
45
+ case <- ctx .Done ():
46
+ return ctx .Err ().Error ()
47
+ default :
48
+ }
49
+ return "fail"
50
+ }
Original file line number Diff line number Diff line change @@ -76,6 +76,10 @@ func ContextWithDeadline() {
76
76
req = req .WithContext (ctx )
77
77
client := & http.Client {}
78
78
res , err := client .Do (req )
79
+ if err != nil {
80
+ return
81
+ }
82
+ defer res .Body .Close ()
79
83
80
84
}
81
85
You can’t perform that action at this time.
0 commit comments