Skip to content

Instantly share code, notes, and snippets.

@jhnlsn
Created February 18, 2014 20:44
Show Gist options
  • Save jhnlsn/9079684 to your computer and use it in GitHub Desktop.
Save jhnlsn/9079684 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
t0 := time.Now()
url := "http://www.npr.org/robots.txt"
asyncHttpGets(url)
t1 := time.Now()
fmt.Printf("Total call took %v to run.\n", t1.Sub(t0))
}
type HttpResponse struct {
url string
response *http.Response
err error
}
func send(url string, ch chan *HttpResponse) {
t0 := time.Now()
resp, err := http.Get(url)
t1 := time.Now()
fmt.Printf("single request took %v to run.\n", t1.Sub(t0))
ch <- &HttpResponse{url, resp, err}
}
func asyncHttpGets(url string) []*HttpResponse {
total := 100
ch := make(chan *HttpResponse)
responses := []*HttpResponse{}
for i := 0; i< total; i++ {
go send(url, ch)
}
for {
select {
case r := <-ch:
responses = append(responses, r)
if len(responses) == total {
return responses
}
}
}
return responses
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment