Skip to content

Instantly share code, notes, and snippets.

@ricogallo
Created December 2, 2012 02:49
Show Gist options
  • Save ricogallo/4186700 to your computer and use it in GitHub Desktop.
Save ricogallo/4186700 to your computer and use it in GitHub Desktop.
async http get from @merbivore, now refactored away
package main
import (
"fmt"
"net/http"
)
var urls = []string{
"http://www.google.com/",
"http://www.facebook.com/",
"http://news.ycombinator.com/",
}
type HttpResponse struct {
url string
response *http.Response
err error
}
func AsyncHttpGets(urls []string) chan *HttpResponse {
responses := make(chan *HttpResponse, len(urls))
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s \n", url)
resp, err := http.Get(url)
responses <- &HttpResponse{url, resp, err}
}(url)
}
return responses
}
func main() {
channel := AsyncHttpGets(urls)
for i := 0; i < cap(channel); i++ {
result := <-channel
fmt.Printf("%s status: %s\n", result.url,
result.response.Status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment