/
file_downloader.go
57 lines (49 loc) · 1.06 KB
/
file_downloader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package volumeadmin
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/asaskevich/govalidator"
)
type FileDownloader struct{}
func (fd FileDownloader) Download(source string) (*os.File, error) {
tmpFile, err := ioutil.TempFile("", "download")
if err != nil {
return nil, err
}
defer tmpFile.Close()
var content io.ReadCloser
isURL := govalidator.IsURL(source)
if isURL {
content, err = fromHTTP(source)
} else if _, err := os.Stat(source); err == nil {
content, err = fromFileSystem(source)
} else {
return nil, fmt.Errorf("Source is neither a valid url nor a valid file path: %s", source)
}
if err != nil {
return nil, err
}
defer content.Close()
_, err = io.Copy(tmpFile, content)
if err != nil {
return nil, err
}
return tmpFile, nil
}
func fromHTTP(source string) (io.ReadCloser, error) {
response, err := http.Get(source)
if err != nil {
return nil, err
}
return response.Body, nil
}
func fromFileSystem(source string) (io.ReadCloser, error) {
f, err := os.Open(source)
if err != nil {
return nil, err
}
return f, nil
}