Recently, I talked about asynchronous page loads in Perl three different ways (using AnyEvent, Mojolicious, and HTTP::Async). Commenters fixed the Mojo example and added an IO::Lambda example. Another poster created a Perl 6 example.
Today, I did it in Go, which has concurrency built in to the language. That is, no special modules are needed to load the pages asynchronously; if we wrote a program to load the pages one after another instead, the import lines would be the same.
package main import ( "fmt" "io" "io/ioutil" "net/http" "time" ) func loadpage (url string, c chan<- string) { start := time.Now() response, error := http.Get(url) if error != nil { c <- fmt.Sprintln(error) return } length, _ := io.Copy(ioutil.Discard, response.Body) response.Body.Close() c <- fmt.Sprintf("%-25s has length %8d and loaded in %.2f s\n", url, length, time.Since(start).Seconds()) } func main() { urls := []string{ "https://www.google.com", "http://www.windley.com/", "https://www.bing.com", "http://www.example.com", "http://www.wetpaint.com", "http://www.uh.cu", } start := time.Now() c := make(chan string) for _, url := range urls { go loadpage(url, c) } for i := range urls { fmt.Print(i, " ", <-c) } fmt.Printf("Total elapsed time %.2f s\n", time.Since(start).Seconds()) }
Running this gives
$ go run apl.go 0 Get https://www.bing.com: certificate is valid for a248.e.akamai.net, *.akamaihd.net, *.akamaihd-staging.net, not www.bing.com 1 https://www.google.com has length 12400 and loaded in 1.01 s 2 http://www.windley.com/ has length 50178 and loaded in 1.04 s 3 http://www.wetpaint.com has length 74952 and loaded in 1.06 s 4 http://www.example.com has length 2966 and loaded in 1.09 s 5 http://www.uh.cu has length 57304 and loaded in 2.97 s Total elapsed time 2.97 s
Nice! I'm still new at Go, but so far I really like it.
Recent Comments