Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
async fetching of urls using goroutines and channels
package main
import (
var urls = []string{
type HttpResponse struct {
url string
response *http.Response
err error
func asyncHttpGets(urls []string) <-chan *HttpResponse {
ch := make(chan *HttpResponse, len(urls)) // buffered
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s \n", url)
resp, err := http.Get(url)
ch <- &HttpResponse{url, resp, err}
return ch
func main() {
results := asyncHttpGets(urls)
for _ = range urls {
result := <-results
fmt.Printf("%s status: %s\n", result.url, result.response.Status)

This comment has been minimized.

Copy link

@RickyS RickyS commented Jun 4, 2013

resp.Body.Close() on line 26 will panic if given a fake url in the 'urls' array, since 'resp' will be nil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.