package main import ( "fmt" "io" "log" "net/http" "net/http/httputil" "net/url" ) func httpUserInfo(w http.ResponseWriter, r *http.Request) { ret := "your addr is:" + r.RemoteAddr + "\r\n" ret += "request headers:" + fmt.Sprint(r.Header) io.WriteString(w, ret) } func main() { targetURL, err := url.Parse("http://127.0.0.1:80") log.Println("program start......") if err != nil { log.Println("bad url:", err) return } httpProxy := httputil.NewSingleHostReverseProxy(targetURL) http.HandleFunc("/myinfo/", httpUserInfo) http.Handle("/", httpProxy) log.Println("listen http proxy on :8001.....") http.ListenAndServe(":8001", nil) }
以上代码有个缺陷,就是通过HTTP代理后HTTP协议头的Host域不会改变,如代理到 www.qq.com,抓包时:
GET / HTTP/1.1
Host: 127.0.0.1:8001
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Accept: text/html, application/xhtml+xml, */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN
X-Forwarded-For: 192.168.20.155
在服务器没有检查host域的时候用这种方式代理最简单。如果检查host域的网站就自己修改包里面的实现或自己处理http包头,也简单。
有疑问加站长微信联系(非本文作者)