mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-24 13:36:03 +03:00
added url fetching example
This commit is contained in:
parent
412871154a
commit
0057f27184
50
concurrency/fetch_urls/main.go
Normal file
50
concurrency/fetch_urls/main.go
Normal file
@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
urls := []string{
|
||||
"http://www.reddit.com/r/aww.json",
|
||||
"http://www.reddit.com/r/funny.json",
|
||||
"http://www.reddit.com/r/programming.json",
|
||||
}
|
||||
|
||||
resc, errc := make(chan string), make(chan error)
|
||||
|
||||
for _, url := range urls {
|
||||
go func(url string) {
|
||||
body, err := fetch(url)
|
||||
if err != nil {
|
||||
errc <- err
|
||||
return
|
||||
}
|
||||
resc <- string(body)
|
||||
}(url)
|
||||
}
|
||||
|
||||
for i := 0; i < len(urls); i++ {
|
||||
select {
|
||||
case res := <-resc:
|
||||
fmt.Println(res)
|
||||
case err := <-errc:
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fetch(url string) (string, error) {
|
||||
res, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(body), nil
|
||||
}
|
Loading…
Reference in New Issue
Block a user