56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
// Package proxy ...
|
|
//
|
|
// Description : 正向代理服务器
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2022-10-08 14:26
|
|
package proxy
|
|
|
|
import (
|
|
"git.zhangdeman.cn/zhangdeman/util"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// Forward 正向代理主干逻辑
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:28 2022/10/8
|
|
func Forward(rw http.ResponseWriter, req *http.Request) {
|
|
// 复制请求
|
|
proxyRequest := new(http.Request)
|
|
*proxyRequest = *req
|
|
if clientIP, _, err := net.SplitHostPort(proxyRequest.RemoteAddr); err == nil {
|
|
if prior, ok := proxyRequest.Header["X-forwarded-For"]; ok {
|
|
clientIP = strings.Join(prior, ", ")+ ", "+clientIP
|
|
}
|
|
proxyRequest.Header.Set("X-Forwarded-For", clientIP)
|
|
}
|
|
// 请求代理机器IP
|
|
proxyIP := util.IP.GetHostIP()
|
|
proxyRequest.Header.Set("X-Forward-Proxy-IP", proxyIP)
|
|
|
|
// 请求目标服务
|
|
transport := http.DefaultTransport
|
|
res, err := transport.RoundTrip(proxyRequest)
|
|
if nil != err {
|
|
rw.WriteHeader(http.StatusBadGateway)
|
|
return
|
|
}
|
|
// 回写客户端响应头
|
|
for key, values := range res.Header {
|
|
for _, v := range values {
|
|
rw.Header().Add(key, v)
|
|
}
|
|
}
|
|
// 回写客户端状态码
|
|
rw.WriteHeader(res.StatusCode)
|
|
// 回写响应体
|
|
io.Copy(rw, res.Body)
|
|
res.Body.Close()
|
|
}
|