This repository has been archived by the owner on Sep 7, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
93 lines (75 loc) · 1.88 KB
/
http.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
package maven
import (
"github.com/SpongePowered/DownloadIndexer/httperror"
"io"
"net/http"
"net/url"
"os"
)
func createHTTP(url *url.URL) (*httpRepository, error) {
repo := &httpRepository{user: url.User}
url.User = nil
repo.url = url.String()
durl, ok := os.LookupEnv("HTTP_DOWNLOAD_URL")
if ok {
repo.downloadURL = durl
} else {
repo.downloadURL = repo.url
}
return repo, nil
}
type httpRepository struct {
url string
downloadURL string
user *url.Userinfo
}
func (repo *httpRepository) prepareRequest(method string, path string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(method, path, body)
if err != nil {
return
}
// Setup authentication
if repo.user != nil {
password, _ := repo.user.Password()
req.SetBasicAuth(repo.user.Username(), password)
}
return
}
func doRequest(req *http.Request) (resp *http.Response, err error) {
resp, err = http.DefaultClient.Do(req)
if err != nil {
err = httperror.New(http.StatusBadGateway, "Failed to contact upstream server", err)
}
return
}
func (repo *httpRepository) Download(path string, writer io.Writer) error {
req, err := repo.prepareRequest(http.MethodGet, repo.downloadURL+path, nil)
if err != nil {
return err
}
resp, err := doRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
io.Copy(writer, resp.Body)
return nil
}
return httperror.New(resp.StatusCode, "Failed to download file", nil)
}
func (repo *httpRepository) Upload(path string, reader io.Reader, len int64) error {
req, err := repo.prepareRequest(http.MethodPut, repo.url+path, reader)
if err != nil {
return err
}
req.ContentLength = len
resp, err := doRequest(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
return nil
}
return httperror.New(resp.StatusCode, "Failed to upload file", nil)
}