-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
97 lines (88 loc) · 2.09 KB
/
proxy.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
package kakaxi
import (
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"time"
)
func ProxyHTTP(req Request) (resp Response, err error) {
URL := req.URL
savePath := URL.Host + URL.Path
if path.Ext(savePath) == "" {
savePath = savePath + "/index.html"
}
savePath = path.Join("dao/target", savePath)
exist := FileExist(savePath)
if exist {
if resp, err = FileToHttpResponse(savePath); err != nil {
return
}
} else {
if resp, err = doProxyHTTP(req); err != nil {
return
}
}
go OnResponse(req, resp, !exist, savePath, URL.Host, URL.Path)
return
}
func doProxyHTTP(r Request) (resp Response, err error) {
r.Request.RequestURI = ""
var do *http.Response
do, err = http.DefaultClient.Do(r.Request)
if err != nil {
log.Println("http.DefaultClient.Do", err)
return
}
resp = CopyResponse(do)
return
}
func Writer(w io.Writer, resp Response) {
_, _ = w.Write([]byte(fmt.Sprintf("%s %s\n", resp.Proto, resp.Status)))
for k, hs := range resp.Header {
for _, h := range hs {
_, _ = w.Write([]byte(fmt.Sprintf("%s: %s\n", k, h)))
}
}
_, _ = w.Write([]byte("\n"))
_, _ = w.Write(resp.Body)
}
func FileToHttpResponse(filePath string) (Response, error) {
// 打开文件
file, err := os.Open(filePath)
if err != nil {
log.Printf("os.Open(%s) err:%v\n", filePath, err)
return Response{}, err
}
defer file.Close()
// 读取文件内容
content, err := io.ReadAll(file)
if err != nil {
log.Printf("io.ReadAll(%s) err:%v\n", filePath, err)
return Response{}, err
}
// 获取文件信息
fileInfo, err := file.Stat()
if err != nil {
log.Printf("file.Stat(%s) err:%v\n", filePath, err)
return Response{}, err
}
// 获取文件类型
contentType := http.DetectContentType(content)
// 构造 Response
response := Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.1",
Body: content,
Header: http.Header{
"Content-Type": []string{contentType},
"Content-Length": []string{string(fileInfo.Size())},
"Last-Modified": []string{fileInfo.ModTime().Format(time.RFC1123)},
"Accept-Ranges": []string{"bytes"},
},
}
return response, nil
}