github.com/coreos/goproxy@v0.0.0-20190513173959-f8dc2d7ba04e/examples/goproxy-eavesdropper/main.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "flag" 6 "log" 7 "net" 8 "net/http" 9 "regexp" 10 11 "github.com/elazarl/goproxy" 12 ) 13 14 func orPanic(err error) { 15 if err != nil { 16 panic(err) 17 } 18 } 19 20 func main() { 21 proxy := goproxy.NewProxyHttpServer() 22 proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*baidu.com$"))). 23 HandleConnect(goproxy.AlwaysReject) 24 proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))). 25 HandleConnect(goproxy.AlwaysMitm) 26 // enable curl -p for all hosts on port 80 27 proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))). 28 HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) { 29 defer func() { 30 if e := recover(); e != nil { 31 ctx.Logf("error connecting to remote: %v", e) 32 client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n")) 33 } 34 client.Close() 35 }() 36 clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client)) 37 remote, err := net.Dial("tcp", req.URL.Host) 38 orPanic(err) 39 remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote)) 40 for { 41 req, err := http.ReadRequest(clientBuf.Reader) 42 orPanic(err) 43 orPanic(req.Write(remoteBuf)) 44 orPanic(remoteBuf.Flush()) 45 resp, err := http.ReadResponse(remoteBuf.Reader, req) 46 orPanic(err) 47 orPanic(resp.Write(clientBuf.Writer)) 48 orPanic(clientBuf.Flush()) 49 } 50 }) 51 verbose := flag.Bool("v", false, "should every proxy request be logged to stdout") 52 addr := flag.String("addr", ":8080", "proxy listen address") 53 flag.Parse() 54 proxy.Verbose = *verbose 55 log.Fatal(http.ListenAndServe(*addr, proxy)) 56 }