Last active
August 29, 2015 14:02
-
-
Save ddombrow/f3b831d6a56e11826c4a to your computer and use it in GitHub Desktop.
golang channel question
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" | |
"net/http" | |
"sync" | |
) | |
type WebResponse struct { | |
url string | |
response *http.Response | |
err error | |
} | |
var urls = []string{ | |
"http://google.com", | |
"http://yahoo.com", | |
"http://msn.com", | |
} | |
var wg sync.WaitGroup | |
func asyncGetUrl(url string, ch chan *WebResponse) { | |
defer wg.Done() | |
resp, err := http.Get(url) | |
resp.Body.Close() | |
ch <- &WebResponse{url, resp, err} | |
} | |
func main() { | |
ch := make(chan *WebResponse, len(urls)) | |
for _, url := range urls { | |
wg.Add(1) | |
go asyncGetUrl(url, ch) | |
} | |
go func() { | |
wg.Wait() | |
close(ch) | |
}() | |
for r := range ch { | |
fmt.Printf("%s \n", r.url) | |
fmt.Printf("%s \n", r.response.Proto) | |
fmt.Printf("%s \n\n", r.response.Status) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment