我正在尝试使用 Golang 创建一个 HTTP/HTTPS 代理,就像这个链接一样。这是我的所有代码:首先从浏览器获取命令。如果它是 CONNECT 意味着 HTTPS 并制作简单的 TCP 套接字并让浏览器继续它。然后将每个连接通过管道连接在一起。
package main
import (
"bufio"
"fmt"
"net"
"strings"
)
func main() {
fmt.Println("Start server...")
ln, _ := net.Listen("tcp", ":8000")
conn, _ := ln.Accept()
handleSocket(conn)
}
func handleSocket(client_to_proxy net.Conn) {
message, e := bufio.NewReader(client_to_proxy).ReadString('\n')
message = strings.ReplaceAll(message, "\r\n", "")
if e != nil {
fmt.Println("ERROR1 ", e)
return
}
splited := strings.Split(message, " ")
host := strings.Split(splited[1], ":")
if splited[0] == "CONNECT" {
proxy_to_server, e := net.Dial("tcp", splited[1])
if e != nil {
fmt.Println("ERROR2 ", e)
return
}
lenn, e := client_to_proxy.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
if e != nil {
fmt.Println("ERROR8 ", e)
return
}
fmt.Println(lenn)
readAll(client_to_proxy, proxy_to_server)
} else if splited[0] == "GET" {
remote_conn, e := net.Dial("tcp", strings.Replace(splited[1][:len(splited[1])-1], "http://", "", 2)+":80")
if e != nil {
fmt.Println("ERROR7 ", e)
return
}
_, e = remote_conn.Write([]byte("GET / " + splited[2] + "\r\n" + "Host: " + host[0] + "\r\n\r\n"))
if e != nil {
fmt.Println("ERROR6 ", e)
return
}
writeAll(client_to_proxy, remote_conn)
}
}
func writeAll(client_to_proxy net.Conn, proxy_to_server net.Conn) {
buffer := make([]byte, 32*1024)
for {
readLeng, err := proxy_to_server.Read(buffer)
if err != nil {
fmt.Println("ERROR9 ", err)
return
}
if readLeng > 0 {
_, err := client_to_proxy.Write(buffer)
if err != nil {
fmt.Println("ERR4 ", err)
return
}
}
}
}
蛊毒传说
江户川乱折腾
相关分类