一个超级简单的 http Proxy ,实现本机代理,在pad 上方便的访问公司vpn内的资源
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/url"
"strings"
)
func main() {
var port string = "8888"
li, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Println("error listent ", err)
return
}
defer li.Close()
log.Println("开启监听端口 "+port)
var i int
//死循环监听
clientData := make([] byte, 4096)
for {
client, err := li.Accept();
if err != nil {
log.Println("监听错误", err)
break
}
i++
n, err := client.Read(clientData)
requestStrings:=string(clientData[:n])
log.Println("client request : \n ", requestStrings)
var method,uri, host, address string
//取第一行
fmt.Sscanf(string(clientData[:bytes.IndexByte(clientData, '\n')]), "%s%s", &method, &uri)
key:=strings.Split(requestStrings,"\n")
for _,c :=range( key) {
if strings.Index(c,"Host")!=-1{
host=c[strings.Index(c,"Host:")+5 :]
host=strings.TrimSpace(host)
}
}
fmt.Printf("methods [%s],Host [%s]\n",method,host)
//判断url有没有接口
if strings.Index(uri, "http:") >0 {
parseUrl,err:=url.Parse(uri)
if err!= nil{
log.Println("error",err)
}
address=parseUrl.Host
} else if strings.Index(uri, ":443") >0 {
address = host + ":443"
}else{
address = host + ":80"
}
//获得了请求host和port,开始拨号进行tcp连接
server, err := net.Dial("tcp", address)
if err != nil {
log.Println(err)
continue
}
if method == "CONNECT" {
fmt.Fprint(client, "HTTP/1.1 200 Connection established\r\n\r\n")
} else {
server.Write(clientData[:n])
}
go io.Copy(server, client)
go io.Copy(client, server)
}
}
网友评论