Last active
December 29, 2015 16:49
-
-
Save hazbo/7699986 to your computer and use it in GitHub Desktop.
First attempt of concurrency 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
package main | |
import( | |
"fmt" | |
"net/http" | |
"time" | |
"io/ioutil" | |
) | |
type ResponseData struct { | |
nanoseconds int64 | |
} | |
func main() { | |
data := make(chan * ResponseData) | |
go MakeRequest("http://google.com", data) | |
go MakeRequest("http://github.com", data) | |
go MakeRequest("http://facebook.com", data) | |
fmt.Println("Do something...") | |
data <- new(ResponseData) | |
time.Sleep(1 * time.Second) | |
fmt.Println("Do something else...") | |
time.Sleep(3 * time.Second) | |
fmt.Println("Last thing!") | |
<- data | |
} | |
func MakeRequest(url string, response_data chan * ResponseData) { | |
data := <- response_data | |
t0 := time.Now() | |
response, err := http.Get(url) | |
if (err == nil) { | |
response_body, err := ioutil.ReadAll(response.Body) | |
if (err == nil) { | |
response_string := string(response_body) | |
if (response_string != "") { | |
t1 := time.Now() | |
data.nanoseconds = t1.Sub(t0).Nanoseconds() | |
fmt.Println("Request took", data.nanoseconds, "nanoseconds.") | |
response_data <- data | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment