1 回答
TA贡献1789条经验 获得超10个赞
你可以使用 httputil
你可以做类似下面的事情。
对于代理 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)
}
对于代理 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)
}
编辑:
要处理每个代理的请求正文,您可以查看此内容。或者,我认为基于当前要求构建新要求应该没有坏处,如下所示:
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)
}
这可以在两个代理上完成。
编辑:
代理响应可以使用 ReverseProxy.ModifyResponse 进行更新。
你可以这样使用它:
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 关注
- 204 浏览
添加回答
举报