-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
59 lines (52 loc) · 1.46 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
package bec_http
import (
"io"
"log"
"net/http"
"strings"
)
// urlPath should be like `/foo/`, mind the trailing slash
func ProxyHandler(urlPath, proxyURL string, allowPrefix []string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
reqURI := r.RequestURI
targetStr := strings.TrimPrefix(reqURI, urlPath)
var found bool
for _, p := range allowPrefix {
if strings.HasPrefix(targetStr, p) {
found = true
}
}
if !found {
log.Println("Failed to match allowPrefix", targetStr)
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
targetURL := "https://" + targetStr
// 创建一个新的请求,并复制原始请求的信息
proxyReq, err := http.NewRequest(r.Method, proxyURL+targetURL, r.Body)
if err != nil {
log.Println("Failed to new request", targetURL)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
proxyReq.Header = r.Header
// 使用http.Client来发送新的请求
client := &http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
log.Println("Failed to send request", targetURL)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// 将响应头复制到原始客户端的响应
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.StatusCode)
// 将响应体复制到原始客户端
io.Copy(w, resp.Body)
}
}