| 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.*:443$"))). |
| 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 |
client.Write([]byte("HTTP/1.1 200 Ok\r\n\r\n")) |
| 40 |
remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote)) |
| 41 |
for { |
| 42 |
req, err := http.ReadRequest(clientBuf.Reader) |
| 43 |
orPanic(err) |
| 44 |
orPanic(req.Write(remoteBuf)) |
| 45 |
orPanic(remoteBuf.Flush()) |
| 46 |
resp, err := http.ReadResponse(remoteBuf.Reader, req) |
| 47 |
orPanic(err) |
| 48 |
orPanic(resp.Write(clientBuf.Writer)) |
| 49 |
orPanic(clientBuf.Flush()) |
| 50 |
} |
| 51 |
}) |
| 52 |
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout") |
| 53 |
addr := flag.String("addr", ":8080", "proxy listen address") |
| 54 |
flag.Parse() |
| 55 |
proxy.Verbose = *verbose |
| 56 |
log.Fatal(http.ListenAndServe(*addr, proxy)) |
| 57 |
} |