downloader/main.go

70 lines
1.2 KiB
Go

package main
import (
"io"
"log"
"net"
"net/http"
"os"
"strings"
"time"
)
func main() {
entries := os.Args[1:]
c := make(chan error)
d := Downloader{}
d.HTTPClient.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 90 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
for _, u := range entries {
splits := strings.Split(u, ";")
url := splits[0]
output := splits[1]
go d.download(url, output, c)
}
for range entries {
err := <-c
if err != nil {
log.Panic(err)
}
}
}
type Downloader struct {
HTTPClient http.Client
}
func (d *Downloader) download(url string, output string, doneChan chan error) {
res, err := d.HTTPClient.Get(url)
if err != nil {
doneChan <- err
return
}
if res.StatusCode != http.StatusOK {
doneChan <- nil
return
}
f, err := os.Create(output)
if err != nil {
doneChan <- err
return
}
_, err = io.Copy(f, res.Body)
if err != nil {
doneChan <- err
return
}
doneChan <- nil
}