-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContextDemo.go
72 lines (53 loc) · 1.08 KB
/
ContextDemo.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
package main
import (
"context"
"fmt"
"net/http"
"time"
)
type resultN1 struct{
url string
err error
latency time.Duration
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(),250*time.Millisecond)
defer cancel()
resultT := make(chan resultN1)
list := []string{
"http://www.google.com",
"http://www.apple.com",
"http://www.amazon.com",
}
for _, n:= range list{
go getData(ctx,n, resultT)
}
for range list {
select{
case dt:= <-resultT:
if dt.err != nil{
fmt.Println("Error getting data from", dt.url)
}else{
fmt.Println("Getting data from" ,dt.url," in",dt.latency,"seconds" )
}
case <-ctx.Done():
fmt.Println("request timed out")
}
}
}
func getData(ctx context.Context,url string, ch chan<- resultN1){
start:= time.Now()
req, _:= http.NewRequestWithContext(ctx, "GET",url,nil)
if resp, err := http.DefaultClient.Do(req); err != nil{
ch <- resultN1{
url,
nil,
0,
}
resp.Body.Close()
}else{
t:= time.Since(start).Round(time.Millisecond)
ch<- resultN1{url, nil, t}
resp.Body.Close()
}
}