Skip to content

Instantly share code, notes, and snippets.

@michaljemala
Created October 19, 2015 13:13
Show Gist options
  • Save michaljemala/73dde464b6b78becf2d1 to your computer and use it in GitHub Desktop.
Save michaljemala/73dde464b6b78becf2d1 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
)
func main() {
urls := []string{
"http://www.reddit.com/r/programming.go",
}
// a channel
jsonResponses := make(chan string)
var wg sync.WaitGroup //def.1
wg.Add(len(urls)) //def.2
for _, url := range urls {
// as many goroutines as there are urls !
// Note the way each goroutine gets a different url value,
// through the use of an "anonymous closure".
// The current url is passed to the closure as a parameter,
// masking the url variable from the outer for-loop.
// This allows each goroutine to have its own copy of url;
// otherwise, the next iteration of the for-loop would update url in all
// goroutines.
go func(url string) {
defer wg.Done() //def.3, inside each Goroutines
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) //send on channel
}
}
}(url)
}
go func() {
wg.Wait() //def.4
// finished... close the channel
close(jsonResponses)
}()
for response := range jsonResponses { //receive on channel until we consumed everything
fmt.Println(response)
}
}
/* Expected Output:
A list of .... text in json format.
*/
@patrickToca
Copy link

Correct. Version 3... to come... and maybe version 4...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment