-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpRequestWithContext.go
63 lines (47 loc) · 1.04 KB
/
HttpRequestWithContext.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
package main
import (
"context"
"fmt"
"net/http"
"time"
)
type result struct {
url string
err error
latency time.Duration
}
func get(ctx context.Context, url string, ch chan<- result) {
start := time.Now()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if resp, err := http.DefaultClient.Do(req); err != nil {
ch <- result{url, err, 0}
resp.Body.Close()
} else {
t := time.Since(start).Round(time.Millisecond)
ch <- result{url, nil, t}
resp.Body.Close()
}
}
func main() {
results := make(chan result)
list := []string{
"https://amazon.com",
"https://apple.com",
"https://google.com",
"https://wsm.com",
// "http://localhost:8080",
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
for _, url := range list {
go get(ctx, url, results)
}
for range list {
r := <-results
if r.err != nil {
fmt.Printf("Erros is %s and url is %v\n", r.err, r.url)
} else {
fmt.Printf("Data received in %v and url is %s\n", r.latency, r.url)
}
}
}