-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
48 lines (40 loc) · 1014 Bytes
/
fetch.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 fan
import (
"fmt"
"io"
"math/rand"
"net/http"
"os"
"path/filepath"
)
const suffixCharset = "abcdefhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func randomSuffix(l int) string {
suffix := make([]byte, l)
for i := range suffix {
suffix[i] = suffixCharset[rand.Intn(len(suffixCharset))]
}
return string(suffix)
}
// todo: check content-type header
// todo: add authentication stuff (certs)
func FetchToPath(u string, path string) (string, error) {
out, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer out.Close()
resp, err := http.Get(u)
if err != nil {
return "", err
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return "", fmt.Errorf("failed to write to file: %w", err)
}
return out.Name(), nil
}
func Fetch(u string) (string, error) {
path := filepath.Join(os.TempDir(), "fan-"+randomSuffix(8))
return FetchToPath(u, path)
}