package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	CheckHttpArgs(os.Args[1:])
	start := time.Now()
	ch := make(chan string)
	for _, url := range os.Args[1:] {
		go fetch(url, ch)
	}
	for range os.Args[1:] {
		fmt.Println(<-ch)
	}
	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.Sprintln(err)
		return
	}
	nbyte, err := io.Copy(io.Discard, resp.Body)
	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, nbyte, url)
}

func CheckHttpArgs(args []string) {
	for i, _ := range args {
		// 去除空格
		strings.TrimSpace(args[i])
		// 去除 /
		strings.Trim(args[i], "/")

		if strings.HasPrefix(args[i], "http") != true {
			args[i] = "http://" + args[i]
		}
	}
}
