Created
September 11, 2015 05:03
-
-
Save rockybean/7536ee4caf49a07b3a9f to your computer and use it in GitHub Desktop.
Go WaitGroup Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"sync" | |
) | |
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", | |
} | |
jsonResponses := make(chan string) | |
var wg sync.WaitGroup | |
wg.Add(len(urls)) | |
for _, url := range urls { | |
go func(url string) { | |
defer wg.Done() | |
res, err := http.Get(url) | |
if err != nil { | |
log.Fatal(err) | |
} else { | |
defer res.Body.Close() | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
log.Fatal(err) | |
} else { | |
jsonResponses <- string(body) | |
} | |
} | |
}(url) | |
} | |
go func() { | |
for response := range jsonResponses { | |
fmt.Println(response) | |
} | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment