Skip to content

Instantly share code, notes, and snippets.

@brownhash
Created January 20, 2020 18:47
Show Gist options
  • Save brownhash/ed3900bdd3cb936785e684a77088d695 to your computer and use it in GitHub Desktop.
Save brownhash/ed3900bdd3cb936785e684a77088d695 to your computer and use it in GitHub Desktop.
Using GoRoutines
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
ch := make(chan string) // created a channel
for _, urls := range os.Args[1:] {
go fetch(urls, ch) // staring a go routine
}
for range os.Args[1:] {
fmt.Println(<-ch) // fetch data from go routine through channel
}
fmt.Printf("%2fs elapsed\n", time.Since(start).Seconds())
}
func fetch(url string, ch chan<- string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err) // send error message to channel
return
}
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
if err != nil {
ch<- fmt.Sprintf("while reading %s: %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%2fs %7d %s", secs, nbytes, url)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment