shad-go/fetchall/main.go

57 lines
1,004 B
Go
Raw Permalink Normal View History

2022-02-10 22:06:57 +00:00
//go:build !solution
2020-02-13 16:00:29 +00:00
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
type HTTPGetResult struct {
Success bool
Body string
Elapsed time.Duration
Size int
URL string
Error error
}
func (result HTTPGetResult) String() string {
if result.Success {
return fmt.Sprintf("%v\t%v\t%v", result.Elapsed, result.Size, result.URL)
} else {
return result.Error.Error()
}
}
2024-06-05 23:15:25 +00:00
func GetHTTPBody(url string, ch chan string) {
startTime := time.Now()
resp, err := http.Get(url)
if err != nil {
2024-06-05 23:15:25 +00:00
ch <- fmt.Sprint(err)
return
}
defer resp.Body.Close()
2024-06-05 23:15:25 +00:00
n, err := io.Copy(io.Discard, resp.Body)
if err != nil {
2024-06-05 23:15:25 +00:00
ch <- fmt.Sprint(err)
return
}
2024-06-05 23:15:25 +00:00
ch <- fmt.Sprintf("%.2fs\t%v\t%v", time.Since(startTime).Seconds(), n, url)
}
2020-02-13 16:00:29 +00:00
func main() {
startTime := time.Now()
2024-06-05 23:15:25 +00:00
urls, ch := os.Args[1:], make(chan string)
for _, url := range urls {
go GetHTTPBody(url, ch)
}
2024-06-05 23:15:25 +00:00
for range urls {
fmt.Println(<-ch)
}
2024-06-05 23:15:25 +00:00
fmt.Printf("%.2fs elapsed\n", time.Since(startTime).Seconds())
2020-02-13 16:00:29 +00:00
}