Merge pull request #9 from ttlbb/dev

add http/https proxy
This commit is contained in:
SanJin 2019-08-16 10:28:39 +08:00 committed by GitHub
commit beed40bdb5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,53 +1,30 @@
package httpx package httpx
import ( import (
"fmt"
"io"
"net"
"net/http" "net/http"
"strings" "github.com/elazarl/goproxy"
"net/url"
"fmt"
) )
/*http 正向代理*/ /*http 正向代理*/
type Pxy struct{} func Start(addr string, proxyUrl string) {
func (p *Pxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { gp := goproxy.NewProxyHttpServer()
fmt.Printf("Received request %s %s %s\n", req.Method, req.Host, req.RemoteAddr) pu, err := url.Parse(proxyUrl)
if err == nil {
transport := http.DefaultTransport gp.Tr.Proxy = http.ProxyURL(&url.URL{
Scheme: pu.Scheme,
// step 1 Host: pu.Host,
outReq := new(http.Request) })
*outReq = *req // this only does shallow copies of maps
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
if prior, ok := outReq.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
outReq.Header.Set("X-Forwarded-For", clientIP)
} }
// step 2 gp.OnRequest().HandleConnect(goproxy.AlwaysMitm)
res, err := transport.RoundTrip(outReq) gp.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
if err != nil { // Report Send
rw.WriteHeader(http.StatusBadGateway) fmt.Println(req.RemoteAddr)
return return req, nil
} })
http.ListenAndServe(addr, gp)
// step 3 }
for key, value := range res.Header {
for _, v := range value {
rw.Header().Add(key, v)
}
}
rw.WriteHeader(res.StatusCode)
io.Copy(rw, res.Body)
res.Body.Close()
}
func Start(addr string) {
http.Handle("/", &Pxy{})
http.ListenAndServe(addr, nil)
}