Last active
September 17, 2015 10:09
-
-
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
This file contains hidden or 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
// 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