-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathDownloader.go
60 lines (52 loc) · 1.38 KB
/
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
58
59
60
package docxplate
import (
"context"
"crypto/md5" // #nosec G501 - allowed weak hash here
"fmt"
"io"
"log"
"net/http"
"os"
"path"
)
// DownloadClient to use instead of default http.Client
type DownloadClient struct {
}
// Downloader ..
type Downloader interface {
DownloadFile(ctx context.Context, urlStr string) (tmpFile string, err error)
}
// DefaultDownloader to use as default client
var DefaultDownloader Downloader = &DownloadClient{}
// DownloadFile (satisfy interface) Download url file
func (DownloadClient) DownloadFile(_ context.Context, urlStr string) (tmpFile string, err error) {
resp, err := http.Get(urlStr) // #nosec G107 - allowed url variable here
if err != nil {
return "", err
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("download: remove: %s", err)
}
}()
if resp.StatusCode != http.StatusOK {
return "", http.ErrMissingFile
}
// Create file
tmpFile = fmt.Sprintf("%x%s", md5.Sum([]byte(urlStr)), path.Ext(urlStr)) // #nosec G401 - allowed weak hash here
out, err := os.Create(tmpFile) // #nosec G304 - allowed filename variable here
if err != nil {
return
}
defer func() {
if err := out.Close(); err != nil {
log.Printf("download: close: %s", err)
}
}()
// Write body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return
}
return tmpFile, nil
}