Created
February 18, 2014 20:44
-
-
Save jhnlsn/9079684 to your computer and use it in GitHub Desktop.
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" | |
"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