-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
76 lines (63 loc) · 1.32 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
package main
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
"net/http"
"path"
)
type CachedHttpClient struct {
Client *http.Client
CacheDir string
}
func NewCachedHttpClient(cacheDir string) (*CachedHttpClient, error) {
if cacheDir != "" {
err := DirExists(cacheDir, true)
if err != nil {
return nil, err
}
}
c := &CachedHttpClient {
Client: &http.Client{},
CacheDir: cacheDir,
}
return c, nil
}
func (c *CachedHttpClient) GetPageRaw(url string, headers map[string] string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
res, err := c.Client.Do(req)
if err != nil {
return nil, err
}
return res, nil
}
func (c *CachedHttpClient) GetPage(url string, headers map[string] string) (string, error) {
id := ""
if c.CacheDir != "" {
h := md5.New()
h.Write([]byte(url))
id = hex.EncodeToString(h.Sum(nil))
page, err := ioutil.ReadFile(path.Join(c.CacheDir, id))
if err == nil {
return string(page), nil
}
}
res, err := c.GetPageRaw(url, headers)
if err != nil {
return "", err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
if c.CacheDir != "" {
_ = ioutil.WriteFile(path.Join(c.CacheDir, id), data, 0644)
}
return string(data), nil
}