forked from italia/publiccode-parser-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.go
55 lines (45 loc) · 1.07 KB
/
data.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
package publiccode
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path"
"path/filepath"
httpclient "github.com/italia/httpclient-lib-go"
)
// downloadFile download the file in the path.
func downloadFile(filepath string, url *url.URL, headers map[string]string) error {
// Create the file.
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data from the url.
resp, err := httpclient.GetURL(url.String(), headers)
if err != nil {
return err
}
reader := bytes.NewReader(resp.Body)
// Write the body to file.
_, err = io.Copy(out, reader)
return err
}
// Caller is responsible for removing the temporary directory.
func downloadTmpFile(url *url.URL, headers map[string]string) (string, error) {
// Create a temp dir
tmpdir, err := ioutil.TempDir("", "publiccode.yml-parser-go")
if err != nil {
log.Fatal(err)
}
// Download the file in the temp dir.
tmpFile := filepath.Join(tmpdir, path.Base(url.Path))
err = downloadFile(tmpFile, url, headers)
if err != nil {
return "", err
}
return tmpFile, nil
}