forked from deankarn/go-download
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
48 lines (42 loc) · 868 Bytes
/
util.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
package download
import (
"io"
"net/http"
"os"
"path/filepath"
"github.com/webx-top/com"
)
func Download(url, saveName string, options *Options) (int64, error) {
f, err := Open(url, options)
if err != nil {
return 0, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return 0, err
}
var output *os.File
if len(saveName) == 0 {
saveName = info.Name()
} else {
dir := filepath.Dir(saveName)
if err := com.MkdirAll(dir, os.ModePerm); err != nil {
return 0, err
}
}
output, err = os.OpenFile(saveName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766)
if err != nil {
return 0, err
}
defer output.Close()
return io.Copy(output, f)
}
// NewHTTPClient New a client
func NewHTTPClient(options ...com.HTTPClientOptions) *http.Client {
client := &http.Client{}
for _, option := range options {
option(client)
}
return client
}