Skip to content

Commit 5640525

Browse files
committed
通过 context 通知 go 超时退出
1 parent f242053 commit 5640525

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

context/go_ctx.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

context/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ func ContextWithDeadline() {
7676
req = req.WithContext(ctx)
7777
client := &http.Client{}
7878
res, err := client.Do(req)
79+
if err != nil {
80+
return
81+
}
82+
defer res.Body.Close()
7983

8084
}
8185

0 commit comments

Comments
 (0)