forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_download.go
112 lines (88 loc) · 2 KB
/
file_download.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package fileutils
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
type Downloader interface {
DownloadFile(string) (int64, string, error)
RemoveFile() error
}
type downloader struct {
saveDir string
filename string
}
func NewDownloader(saveDir string) Downloader {
return &downloader{
saveDir: saveDir,
}
}
//this func returns byte written, filename and error
func (d *downloader) DownloadFile(url string) (int64, string, error) {
c := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
//some redirect return '/' as url
if strings.Trim(r.URL.Opaque, "/") != "" {
url = r.URL.Opaque
}
return nil
},
}
r, err := c.Get(url)
if err != nil {
return 0, "", err
}
defer r.Body.Close()
if r.StatusCode == 200 {
d.filename = get_filename_from_header(r.Header.Get("Content-Disposition"))
if d.filename == "" {
d.filename = get_filename_from_url(url)
}
f, err := os.Create(filepath.Join(d.saveDir, d.filename))
if err != nil {
return 0, "", err
}
defer f.Close()
size, err := io.Copy(f, r.Body)
if err != nil {
return 0, "", err
}
return size, d.filename, nil
} else {
return 0, "", fmt.Errorf("Error downloading file from %s", url)
}
}
func (d *downloader) RemoveFile() error {
return os.Remove(filepath.Join(d.saveDir, d.filename))
}
func get_filename_from_header(h string) string {
if h == "" {
return ""
}
contents := strings.Split(h, ";")
for _, content := range contents {
if strings.Contains(content, "filename=") {
name := strings.TrimLeft(content, "filename=")
return strings.Trim(name, `"`)
}
}
return ""
}
func get_filename_from_url(url string) string {
tmp := strings.Split(url, "/")
token := tmp[len(tmp)-1]
if i := strings.LastIndex(token, "?"); i != -1 {
token = token[i+1:]
}
if i := strings.LastIndex(token, "&"); i != -1 {
token = token[i+1:]
}
if i := strings.LastIndex(token, "="); i != -1 {
return token[i+1:]
}
return token
}