1 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
你可以使用 httputil
你可以做類似下面的事情。
對(duì)于代理 A:
const (
ServerB = "<address of B>"
Port = "<proxy A port>"
)
func main() {
// start server
http.HandleFunc("/", proxyPass)
log.Fatal(http.ListenAndServe(":" + Port, nil))
}
func proxyPass(res http.ResponseWriter, req *http.Request) {
// Encrypt Request here
// ...
url, _ := url.Parse(ServerB)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(res, req)
}
對(duì)于代理 B:
const (
Server = "<address of server>"
Port = "<proxy B port>"
)
func main() {
// start server
http.HandleFunc("/", proxyPass)
log.Fatal(http.ListenAndServe(":" + Port, nil))
}
func proxyPass(res http.ResponseWriter, req *http.Request) {
// Decrypt Request here
// ...
url, _ := url.Parse(Server)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(res, req)
}
編輯:
要處理每個(gè)代理的請(qǐng)求正文,您可以查看此內(nèi)容?;蛘撸艺J(rèn)為基于當(dāng)前要求構(gòu)建新要求應(yīng)該沒有壞處,如下所示:
func proxyPass(res http.ResponseWriter, req *http.Request) {
body, _ := ioutil.ReadAll(req.Body)
data := string(body)
// process data here
req, _ = http.NewRequest(req.Method, req.URL.String(), strings.NewReader(data))
u, _ := url.Parse(Server)
proxy := httputil.NewSingleHostReverseProxy(u)
proxy.ServeHTTP(res, req)
}
這可以在兩個(gè)代理上完成。
編輯:
代理響應(yīng)可以使用 ReverseProxy.ModifyResponse 進(jìn)行更新。
你可以這樣使用它:
func proxyPass(res http.ResponseWriter, req *http.Request) {
....
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ModifyResponse = func(response *http.Response) error {
// Read and update the response here
// The response here is response from server (proxy B if this is at proxy A)
// It is a pointer, so can be modified to update in place
// It will not be called if Proxy B is unreachable
}
proxy.ServeHTTP(res, req)
}
- 1 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報(bào)