tgpl/ch1/dmfetchall/1_11.go

55 lines
956 B
Go

package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
start := time.Now()
ch := make(chan string)
if len(os.Args[1:]) < 1 {
log.Fatal("needs args")
}
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
go fetch(url, ch)
}
longest := time.After(time.Duration(time.Second))
for range os.Args[1:] {
select {
case s := <-ch:
fmt.Println(s)
case <-longest:
fmt.Println("took too long")
break
}
}
fmt.Printf("%.2fs\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)
return
}
defer resp.Body.Close()
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
ch <- fmt.Sprint(err)
return
}
elapsed := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", elapsed, nbytes, url)
}