package main import ( "bytes" "fmt" "log" "net" "os" "strconv" "strings" "time" "../../RequestCenter" ) func main() { var srcHost, agencyHost string flag.StringVar(&srcHost, "srcHost", "", "srcHost") flag.StringVar(&agencyHost, "agencyHost", "", "agencyHost") flag.Parse() if srcHost == "" || agencyHost == "" { fmt.Fprintf(os.Stderr, "Fatal error: %s", "參數爲空") os.Exit(1) } Log("已成功將" + srcHost + "代理到" + agencyHost) //創建socket,監聽端口 netListen, err := net.Listen("tcp", srcHost) CheckError(err) Log("Waiting for clients") defer netListen.Close() for { conn, err := netListen.Accept() //若是沒有請求就一直等待 if err == nil { Log(conn.RemoteAddr().String(), " tcp connect success ", conn.LocalAddr()) chanmsg := make(chan int) go handleConnection(conn, agencyHost, chanmsg) if <-chanmsg == 1 { conn.Close() //Log("連接被關閉!") } } } } //處理鏈接 func handleConnection(conn net.Conn, agencyHost string, chanmsg chan int) { var baseReq = RequestCenter.CreateRequestWithConn(conn) buffer := baseReq.ReceiveData(5000) if len(buffer) > 1 { arr := strings.Split(string(buffer), "\r\n") if len(arr) > 1 { arr[1] = "Host: " + agencyHost newstr := strings.Join(arr, "\r\n") Log(newstr) SendAgencyHost([]byte(newstr), baseReq, agencyHost) } } chanmsg <- 1 } func SendAgencyHost(data []byte, baseconn *RequestCenter.QRequest, agencyHost string) { var agencyReq = RequestCenter.CreateRequest("tcp", agencyHost) agencyReq.SendData(nil, data) var buf bytes.Buffer bufferHead := agencyReq.ReceiveData(5000) if len(bufferHead) > 0 { buf.Write(bufferHead) } time.Sleep(10 * time.Millisecond) bufferBody := agencyReq.ReceiveData(5000) if len(bufferBody) > 0 { buf.Write(bufferBody) } Log(strconv.Itoa(buf.Len())) Log(string(buf.Bytes())) baseconn.SendData(nil, buf.Bytes()) agencyReq.Close() } //打印信息統一方法 func Log(v ...interface{}) { log.Println(v...) } //執行錯誤處理方法 func CheckError(err error) { if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) os.Exit(1) } }