Am learning Google Go (very interesting, by the way) and the first program I used to learn was Matt Aimonetti's blog post:
package main
import (
"fmt"
"net/http"
"time"
)
var urls = [] string {
"http://golang.org",
"http://www.espn.com",
"http://www.google.com",
}
type HttpResponse struct {
url string
response *http.Response
err error
}
func asyncHttpGets(urls [] string) [] *HttpResponse {
ch := make(chan *HttpResponse)
responses := [] *HttpResponse{}
seconds := 0
for _, url := range urls {
go func(url string) {
fmt.Printf("Fetching %s
", url)
resp, err := http.Get(url)
ch <- &HttpResponse{url, resp, err}
}(url)
}
for {
select {
case r := <-ch:
fmt.Printf("%s was fetched
", r.url)
responses = append(responses, r)
if len(responses) == len(urls) {
return responses
}
case <- time.After(50 * time.Millisecond):
seconds++
fmt.Printf(".")
fmt.Sprintf("%v", seconds)
}
}
return responses
}
func main() {
results := asyncHttpGets(urls)
for _, result := range results {
fmt.Printf("%s status: %s
", result.url, result.response.Status)
}
}
I wanted to see the milliseconds also printed in the output so I create a seconds variable inside the asyncHttpGets method and incremented it in the same place that prints the "."
However, it never displays when I run:
go build concurrency_example.go && ./concurrency_example
Outputs:
Fetching http://golang.org
Fetching http://www.espn.com
Fetching http://www.google.com
...http://www.google.com was fetched
..http://golang.org was fetched
.........http://www.espn.com was fetched
http://www.google.com status: 200 OK
http://golang.org status: 200 OK
http://www.espn.com status: 200 OK
Question(s):
Why isn't the seconds counter being printed?
How do I print it by converting milliseconds to seconds (as int) and then convert to string?
This example and the explanations in the blog post was a great learning experience!