-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmina.go
78 lines (66 loc) · 1.61 KB
/
mina.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
// mina idea and source code forked from github.com/sariina/mina
package main
import (
"bufio"
"bytes"
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
)
func cacheWrite(path string, filename string, body []byte) {
err := os.MkdirAll(path, 0755)
if err != nil {
log.Printf("Error while mkdir: %s", err)
return
}
err = ioutil.WriteFile(filename, body, 0644)
if err != nil {
log.Printf("Error while writing: %s", err)
return
}
}
func isFileExist(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
func requestMD5(req *http.Request) (string, []byte) {
h := md5.New()
body, _ := httputil.DumpRequest(req, true)
io.WriteString(h, fmt.Sprintf("%+v", string(body)))
return fmt.Sprintf("%x", h.Sum(nil)), body
}
func (g *GMina) request(req *http.Request) (*http.Response, error) {
md5, reqDump := requestMD5(req)
reqFilename := filepath.Join(g.CacheDir, fmt.Sprintf("%s.req", md5))
resFilename := filepath.Join(g.CacheDir, fmt.Sprintf("%s.res", md5))
if isFileExist(resFilename) {
resDump, err := ioutil.ReadFile(resFilename)
if err != nil {
return nil, err
}
dumpIO := bufio.NewReader(bytes.NewBuffer(resDump))
resp, err := http.ReadResponse(dumpIO, req)
if err != nil {
return nil, err
}
return resp, nil
} else {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
resDump, err := httputil.DumpResponse(resp, true)
if err != nil {
return nil, err
}
go cacheWrite(g.CacheDir, resFilename, resDump)
go cacheWrite(g.CacheDir, reqFilename, reqDump)
return resp, nil
}
}