Downloading to temp file.

This commit is contained in:
Andrey Smirnov
2013-12-16 00:45:00 +04:00
parent 2c111aaa3b
commit c7cb2a9a83
2 changed files with 52 additions and 0 deletions
+25
View File
@@ -3,6 +3,7 @@ package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
@@ -60,6 +61,30 @@ func (downloader *Downloader) Download(url string, destination string) <-chan er
return ch
}
// DownloadTemp starts new download to temporary file and returns File
//
// Temporary file would be already removed, so no need to cleanup
func (downloader *Downloader) DownloadTemp(url string) (*os.File, error) {
ch := make(chan error, 1)
tempfile, err := ioutil.TempFile(os.TempDir(), "aptly")
if err != nil {
return nil, err
}
defer os.Remove(tempfile.Name())
downloader.queue <- &downloadTask{url: url, destination: tempfile.Name(), result: ch}
err = <-ch
if err != nil {
tempfile.Close()
return nil, err
}
return tempfile, nil
}
// handleTask processes single download task
func (downloader *Downloader) handleTask(task *downloadTask) {
resp, err := http.Get(task.url)
+27
View File
@@ -74,3 +74,30 @@ func (s *DownloaderSuite) TestDownloadFileError(c *C) {
res := <-d.Download("http://smira.ru/", "/no/such/file")
c.Assert(res, ErrorMatches, ".*no such file or directory")
}
func (s *DownloaderSuite) TestDownloadTemp(c *C) {
d := NewDownloader(2)
defer d.Shutdown()
f, err := d.DownloadTemp("http://smira.ru/")
c.Assert(err, IsNil)
defer f.Close()
buf := make([]byte, 1)
f.Read(buf)
c.Assert(buf, DeepEquals, []byte("<"))
_, err = os.Stat(f.Name())
c.Assert(os.IsNotExist(err), Equals, true)
}
func (s *DownloaderSuite) TestDownloadTempError(c *C) {
d := NewDownloader(2)
defer d.Shutdown()
f, err := d.DownloadTemp("http://smira.ru/doesntexist")
c.Assert(err, NotNil)
c.Assert(f, IsNil)
c.Assert(err, ErrorMatches, "HTTP code 404.*")
}