-
Notifications
You must be signed in to change notification settings - Fork 40
/
maybe.go
95 lines (78 loc) · 2.14 KB
/
maybe.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2017 Seamia Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"strings"
"github.com/seamia/tools/support"
)
func downloadFromUrl(url, filename string) (io.Reader, error) {
if downloads, err := support.GetLocation(g_config, "downloads"); err == nil && len(downloads) > 0 {
if len(filename) == 0 {
tokens := strings.Split(url, "/")
filename = path.Join(downloads, tokens[len(tokens)-1])
trace("Downloading", url, "to", filename)
} else {
filename = path.Join(downloads, filename)
}
} else {
alert("the 'download' location is not set")
if err == nil {
err = errors.New("the 'download' location is empty")
}
return nil, err
}
if Exists(filename) {
trace("file already exists. ", url, " maps to ", filename)
return os.Open(filename) // return from cache
}
response, err := http.Get(url)
if err != nil {
alert("Error while downloading", url, "-", err)
return nil, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
alert("got invalid status.code", response.StatusCode, "while downloading", url)
return nil, errors.New("failed to download: " + response.Status)
}
output, err := os.Create(filename)
if err != nil {
alert("Error while creating", filename, "-", err)
return nil, err
}
defer output.Close()
n, err := io.Copy(output, response.Body)
if err != nil {
fmt.Println("Error while downloading", url, "-", err)
return nil, err
}
trace(n, "bytes downloaded.")
return os.Open(filename)
}
func downloadFile(name string) (io.Reader, error) { // todo: need this here?
u, err := url.Parse("https://" + name)
if err != nil {
panic(err)
}
local := support.Hash([]byte(name))
if u.Host == "github.com" {
bits := strings.Split(u.Path, "/")
if len(bits) > 3 {
nnn := make([]string, 0, 20)
nnn = append(nnn, bits[:3]...)
nnn = append(nnn, "raw")
nnn = append(nnn, "master")
nnn = append(nnn, bits[3:]...)
u.Path = strings.Join(nnn, "/")
}
}
return downloadFromUrl(u.String(), local)
}