Skip to content

Instantly share code, notes, and snippets.

@angch
Last active September 17, 2015 10:09
Show Gist options
  • Save angch/bcbf205882011f54ffe7 to your computer and use it in GitHub Desktop.
Save angch/bcbf205882011f54ffe7 to your computer and use it in GitHub Desktop.
quickie rewrite of Python's asyncio http://www.giantflyingsaucer.com/blog/?p=5557 in Go
// quickie rewrite of http://www.giantflyingsaucer.com/blog/?p=5557 in Go
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func fetch_page(url string) chan bool {
c := make(chan bool)
go func(url string, c chan bool) {
response, err := http.Get(url)
if err != nil {
c <- false
} else {
body, _ := ioutil.ReadAll(response.Body)
fmt.Println("URL:", url, "Content: ", string(body))
c <- true
}
}(url, c)
// c is essentially a Future
return c
}
func main() {
tasks := []chan bool{
fetch_page("http://google.com"),
fetch_page("http://cnn.com"),
fetch_page("http://twitter.com"),
}
for _, task := range tasks {
// synchronous wait, but since fetch_page() is running as a goroutine, results
// get printed asynchronously.
// Yes, we can and probably should use sync.WaitGroup, but it'll look different from
// python's asyncio example at http://www.giantflyingsaucer.com/blog/?p=5557
<-task
close(task)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment