-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuller.go
74 lines (67 loc) · 1.74 KB
/
puller.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
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
//RemoteResource a remote resource image/file/etc
type RemoteResource struct {
Filename string
Filetype string
Data []byte
}
func makeRequestReadBytes(url string) []byte {
resp, err := http.Get(url)
if err != nil {
log.Fatalf("Error retrieving %s", url)
}
defer resp.Body.Close()
return readBytesFromBody(resp)
}
func readBytesFromBody(resp *http.Response) []byte {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading response body")
}
return body
}
//RetrieveResource get a remote resource and labe with type.
func RetrieveResource(url string, t string) *RemoteResource {
log.Printf("Retrieiving %q from %q", t, url)
splitName := strings.Split(url, "/")
return &RemoteResource{
Filename: splitName[len(splitName)-1],
Filetype: t,
Data: makeRequestReadBytes(url),
}
}
//SaveResource save the file modeled by the resource to a directory.
func (r *RemoteResource) SaveResource(targetDirectory string) error {
absoluteFileName := targetDirectory + string(filepath.Separator) + r.Filename
log.Printf("Attempting to save file %q", absoluteFileName)
file, err := os.Create(absoluteFileName)
if err != nil {
log.Fatalf("Failed creating file: %s", absoluteFileName)
return err
}
_, err = io.Copy(file, ioutil.NopCloser(bytes.NewBuffer(r.Data)))
if err != nil {
log.Fatalf("Error writing file: %s, %s", absoluteFileName, err)
return err
}
file.Close()
return nil
}
//ToStringForm write string form of object.
func (r *RemoteResource) ToStringForm() string {
return "RemoteResource{\n" +
"Filename: " + r.Filename +
",\n Filetype: " + r.Filetype +
",\n Data: " + string(r.Data) +
"\n}"
}