Skip to content

Instantly share code, notes, and snippets.

@pranjal5215
Created July 29, 2014 20:12
Show Gist options
  • Save pranjal5215/18f95fa506d59db9c740 to your computer and use it in GitHub Desktop.
Save pranjal5215/18f95fa506d59db9c740 to your computer and use it in GitHub Desktop.
Non working code panics on runtime.
package main
import (
"fmt"
"net"
"net/http"
"time"
)
var urls = []string{
"http://pulsoconf.co/",
"http://golang.org/",
"http://matt.aimonetti.net/",
}
var timeout = time.Duration(5e7)
type HttpResponse struct {
url string
response *http.Response
err error
}
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
func asyncHttpGets(urls []string) <-chan *HttpResponse {
ch := make(chan *HttpResponse, len(urls)) // buffered
transport := http.Transport{
Dial: dialTimeout,
}
client := http.Client{
Transport: &transport,
}
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s \n", url)
resp, err := client.Get(url)
if err != nil {
ch <- &HttpResponse{url, nil, err}
}
defer resp.Body.Close()
ch <- &HttpResponse{url, resp, err}
}(url)
}
return ch
}
func main() {
ch := asyncHttpGets(urls)
for _ = range urls {
x := <-ch
fmt.Printf("%s status: %s\n", x.url, x.response.Status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment