-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
99 lines (90 loc) · 1.81 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
94
95
96
97
98
99
package main
import (
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"path/filepath"
"strings"
"time"
)
// global http client
var HClient *http.Client
func init() {
cj, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
HClient = &http.Client{Jar: cj}
}
func HGet(f File) (out File, r io.ReadCloser) {
// TODO: check mimetypes and filename header to determine
// correct filename and extension
if len(f.Path) > 0 && f.Path[len(f.Path)-1] == '/' {
name := filepath.Base(f.Url.Path)
if name == "/" {
// TODO: its probably better to fail here
name = "Noname"
}
}
if filepath.Ext(f.Path) == "" {
ext := filepath.Ext(f.Url.Path)
if ext == ".asp" || ext == ".php" {
ext = ".html"
}
if ext == "" {
ext = ".bin"
}
f.Path += ext
}
resp, err := HClient.Get(f.Url.String())
if err != nil {
out.Err = err
return
}
if resp.StatusCode == 401 {
resp, err = basicAuth(f.Url)
if err != nil {
out.Err = err
return
}
}
sc := resp.StatusCode
if !(sc >= 200 && sc < 300) {
return File{Err: errors.New(f.Url.String() + ": " + resp.Status)}, nil
}
if f.Mtime == (time.Time{}) {
mtime, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
if err != nil {
f.Mtime = time.Now()
}
f.Mtime = mtime
}
return f, resp.Body
}
func basicAuth(u url.URL) (resp *http.Response, err error) {
user, password, err := Keychain(u)
if err != nil {
return
}
req, err := http.NewRequest("GET", u.String(), strings.NewReader(""))
if err != nil {
return
}
req.SetBasicAuth(user, password)
return HClient.Do(req)
}
func grabHttp(rawurl string) (string, error) {
u, e := url.Parse(rawurl)
if e != nil {
return "", e
}
f, r := HGet(File{Url: *u})
if f.Err != nil {
return "", f.Err
}
cont, err := ioutil.ReadAll(r)
return string(cont), err
}