-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.go
81 lines (68 loc) · 1.51 KB
/
shared.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
75
76
77
78
79
80
81
package main
import (
"io"
"math/rand"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
)
func GetRootPath() (string, error) {
hd, err := os.UserHomeDir()
if err != nil {
return "", errors.Wrap(err, "os error")
}
dd := os.Getenv("SNAP_USER_COMMON")
if strings.HasPrefix(dd, filepath.Join(hd, "snap", "go")) || dd == "" {
dd = filepath.Join(hd, "cartoons553")
os.MkdirAll(dd, 0777)
}
return dd, nil
}
func UntestedRandomString(length int) string {
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
const charset = "abcdefghijklmnopqrstuvwxyz1234567890"
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}
func DoesPathExists(p string) bool {
if _, err := os.Stat(p); os.IsNotExist(err) {
return false
}
return true
}
func downloadFile(url, outPath string) error {
if DoesPathExists(outPath) {
return nil
}
// Get the data
resp, err := http.Get(url)
if err != nil {
return errors.Wrap(err, "http error")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "io error")
}
if resp.StatusCode != 200 {
return errors.New(string(body))
}
out, err := os.Create(outPath)
if err != nil {
return errors.Wrap(err, "os error")
}
defer out.Close()
// Write the body to file
_, err = out.Write(body)
if err != nil {
return errors.Wrap(err, "io error")
}
// fmt.Println("Downloaded: " + filepath.Base(url))
return nil
}