-
Notifications
You must be signed in to change notification settings - Fork 7
/
real-life-concurrency-in-go.go
62 lines (56 loc) · 1.15 KB
/
real-life-concurrency-in-go.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
package main
import (
"fmt"
"net/http"
"time"
)
var urls = []string{
"http://www.hao123.com",
"http://www.baidu.com",
"https://ruby-china.org/",
}
type HttpResponse struct {
url string
response *http.Response
err error
}
func asyncHttpGets(urls []string) []*HttpResponse {
ch := make(chan *HttpResponse)
responses := []*HttpResponse{}
client := http.Client{}
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s", url)
resp, err := client.Get(url)
ch <- &HttpResponse{url, resp, err}
if err != nil && resp != nil && resp.StatusCode == http.StatusOK {
resp.Body.Close()
}
}(url)
}
for {
select {
case r := <-ch:
fmt.Printf("%s was fetched\n", r.url)
if r.err != nil {
fmt.Println("with an error", r.err)
}
responses = append(responses, r)
if len(responses) == len(urls) {
return responses
}
default:
fmt.Printf(".")
time.Sleep(50 * time.Millisecond)
}
}
}
func main() {
results := asyncHttpGets(urls)
for _, result := range results {
if result != nil && result.response != nil {
fmt.Printf("%s status: %s\n", result.url,
result.response.Status)
}
}
}