62 lines
1.1 KiB
Go
62 lines
1.1 KiB
Go
//go:build !solution
|
|
|
|
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()
|
|
}
|
|
}
|
|
|
|
func GetHttpBody(url string, ch chan HttpGetResult) {
|
|
startTime := time.Now()
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
ch <- HttpGetResult{Success: false, Error: err}
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
data, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
ch <- HttpGetResult{Success: false, Error: err}
|
|
return
|
|
}
|
|
ch <- HttpGetResult{
|
|
Success: true,
|
|
Body: string(data),
|
|
Elapsed: time.Since(startTime),
|
|
Size: len(data),
|
|
Url: url,
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
startTime := time.Now()
|
|
urls, ch := os.Args[1:], make(chan HttpGetResult)
|
|
for _, url := range urls {
|
|
go GetHttpBody(url, ch)
|
|
}
|
|
for i := 0; i < len(urls); i++ {
|
|
fmt.Println(<-ch)
|
|
}
|
|
fmt.Println(time.Since(startTime), "elapsed")
|
|
}
|