github.com/arunkumar7540/cli@v6.45.0+incompatible/util/download/downloader.go (about) 1 package download 2 3 import ( 4 "io" 5 "io/ioutil" 6 "net" 7 "net/http" 8 "os" 9 "path/filepath" 10 "time" 11 ) 12 13 type Downloader struct { 14 HTTPClient HTTPClient 15 } 16 17 func NewDownloader(dialTimeout time.Duration) *Downloader { 18 tr := &http.Transport{ 19 Proxy: http.ProxyFromEnvironment, 20 DialContext: (&net.Dialer{ 21 KeepAlive: 30 * time.Second, 22 Timeout: dialTimeout, 23 }).DialContext, 24 } 25 26 return &Downloader{ 27 HTTPClient: &http.Client{ 28 Transport: tr, 29 }, 30 } 31 } 32 33 func (downloader Downloader) Download(url string, tmpDirPath string) (string, error) { 34 bpFileName := filepath.Join(tmpDirPath, filepath.Base(url)) 35 36 resp, err := downloader.HTTPClient.Get(url) 37 if err != nil { 38 return bpFileName, err 39 } 40 41 if resp.StatusCode >= 400 { 42 rawBytes, readErr := ioutil.ReadAll(resp.Body) 43 if readErr != nil { 44 return bpFileName, readErr 45 } 46 return bpFileName, RawHTTPStatusError{ 47 Status: resp.Status, 48 RawResponse: rawBytes, 49 } 50 } 51 52 file, err := os.Create(bpFileName) 53 if err != nil { 54 return bpFileName, err 55 } 56 defer file.Close() 57 58 _, err = io.Copy(file, resp.Body) 59 if err != nil { 60 return bpFileName, err 61 } 62 63 return bpFileName, nil 64 }