github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume1/section4/waitgroup/waitgroup.go (about) 1 // An example of concurrently fetching web site URLs using a WaitGroup. 2 package main 3 4 import ( 5 "fmt" 6 "io/ioutil" 7 "log" 8 "net/http" 9 "sync" 10 ) 11 12 func fetchUrl(url string, wg *sync.WaitGroup) { 13 14 // Decrement the WaitGroup counter once we've fetched the URL 15 defer wg.Done() 16 17 response, err := http.Get(url) 18 if err != nil { 19 log.Fatal("Failed to fetch the URL, ", url, " and encountered this error: ", err) 20 } else { 21 fmt.Println("Contents of url, ", url, ", is:\n") 22 contents, err := ioutil.ReadAll(response.Body) 23 24 response.Body.Close() 25 if err != nil { 26 log.Fatal("Failed to read the response body and encountered this error: ", err) 27 } 28 fmt.Println(string(contents), "\n") 29 } 30 31 } 32 33 func main() { 34 35 var wg sync.WaitGroup 36 var urlList = []string{ 37 "http://www.golang.org/", 38 "http://www.google.com/", 39 "http://www.youtube.com/", 40 } 41 42 // Loop through the list of URLs 43 for _, url := range urlList { 44 // Increment the WaitGroup counter 45 wg.Add(1) 46 // Call the fetchURL function as a goroutine to fetch the URL 47 go fetchUrl(url, &wg) 48 } 49 // Wait for the goroutines that are part of the WaitGroup to finish 50 wg.Wait() 51 52 }