Skip to content

Instantly share code, notes, and snippets.

@ddombrow
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddombrow/f3b831d6a56e11826c4a to your computer and use it in GitHub Desktop.
Save ddombrow/f3b831d6a56e11826c4a to your computer and use it in GitHub Desktop.
golang channel question
package main
import (
"fmt"
"net/http"
"sync"
)
type WebResponse struct {
url string
response *http.Response
err error
}
var urls = []string{
"http://google.com",
"http://yahoo.com",
"http://msn.com",
}
var wg sync.WaitGroup
func asyncGetUrl(url string, ch chan *WebResponse) {
defer wg.Done()
resp, err := http.Get(url)
resp.Body.Close()
ch <- &WebResponse{url, resp, err}
}
func main() {
ch := make(chan *WebResponse, len(urls))
for _, url := range urls {
wg.Add(1)
go asyncGetUrl(url, ch)
}
go func() {
wg.Wait()
close(ch)
}()
for r := range ch {
fmt.Printf("%s \n", r.url)
fmt.Printf("%s \n", r.response.Proto)
fmt.Printf("%s \n\n", r.response.Status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment