mirror of
https://github.com/aptly-dev/aptly.git
synced 2026-07-27 13:57:46 +00:00
Downloading to temp file.
This commit is contained in:
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
@@ -60,6 +61,30 @@ func (downloader *Downloader) Download(url string, destination string) <-chan er
|
|||||||
return ch
|
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
|
// handleTask processes single download task
|
||||||
func (downloader *Downloader) handleTask(task *downloadTask) {
|
func (downloader *Downloader) handleTask(task *downloadTask) {
|
||||||
resp, err := http.Get(task.url)
|
resp, err := http.Get(task.url)
|
||||||
|
|||||||
@@ -74,3 +74,30 @@ func (s *DownloaderSuite) TestDownloadFileError(c *C) {
|
|||||||
res := <-d.Download("http://smira.ru/", "/no/such/file")
|
res := <-d.Download("http://smira.ru/", "/no/such/file")
|
||||||
c.Assert(res, ErrorMatches, ".*no such file or directory")
|
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.*")
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user