From 0057f27184c4165ebc94215ed7eec65ca3e16ab7 Mon Sep 17 00:00:00 2001 From: "jian.han" Date: Thu, 25 Jan 2018 11:21:49 +1000 Subject: [PATCH] added url fetching example --- concurrency/fetch_urls/main.go | 50 ++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 concurrency/fetch_urls/main.go diff --git a/concurrency/fetch_urls/main.go b/concurrency/fetch_urls/main.go new file mode 100644 index 0000000..df19145 --- /dev/null +++ b/concurrency/fetch_urls/main.go @@ -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 +}