github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/downloader/downloader.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package downloader 5 6 import ( 7 "io" 8 "net/url" 9 "os" 10 11 "github.com/juju/errors" 12 "github.com/juju/loggo" 13 "github.com/juju/utils" 14 ) 15 16 var logger = loggo.GetLogger("juju.downloader") 17 18 // Downloader provides the functionality for downloading files. 19 type Downloader struct { 20 // OpenBlob is the func used to gain access to the blob, whether 21 // through an HTTP request or some other means. 22 OpenBlob func(*url.URL) (io.ReadCloser, error) 23 } 24 25 // NewArgs holds the arguments to New(). 26 type NewArgs struct { 27 // HostnameVerification is that which should be used for the client. 28 // If it is disableSSLHostnameVerification then a non-validating 29 // client will be used. 30 HostnameVerification utils.SSLHostnameVerification 31 } 32 33 // New returns a new Downloader for the given args. 34 func New(args NewArgs) *Downloader { 35 return &Downloader{ 36 OpenBlob: NewHTTPBlobOpener(args.HostnameVerification), 37 } 38 } 39 40 // Start starts a new download and returns it. 41 func (dlr Downloader) Start(req Request) *Download { 42 return StartDownload(req, dlr.OpenBlob) 43 } 44 45 // Download starts a new download, waits for it to complete, and 46 // returns the local name of the file. The download can be aborted by 47 // closing the Abort channel in the Request provided. 48 func (dlr Downloader) Download(req Request) (string, error) { 49 if err := os.MkdirAll(req.TargetDir, 0755); err != nil { 50 return "", errors.Trace(err) 51 } 52 dl := dlr.Start(req) 53 filename, err := dl.Wait() 54 return filename, errors.Trace(err) 55 }