Created
August 6, 2024 07:57
-
-
Save hightemp/2307623917ed1fdb90f857b6f7cc477e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"log" | |
"net" | |
"strings" | |
) | |
func main() { | |
listener, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
log.Fatal("Failed to start server:", err) | |
} | |
defer listener.Close() | |
fmt.Println("Proxy server listening on :8080") | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
log.Println("Failed to accept connection:", err) | |
continue | |
} | |
go handleConnection(conn) | |
} | |
} | |
func handleConnection(clientConn net.Conn) { | |
defer clientConn.Close() | |
reader := bufio.NewReader(clientConn) | |
requestLine, err := reader.ReadString('\n') | |
if err != nil { | |
log.Println("Error reading request:", err) | |
return | |
} | |
parts := strings.Split(requestLine, " ") | |
if len(parts) != 3 { | |
log.Println("Invalid request line:", requestLine) | |
return | |
} | |
host := parts[1] | |
if !strings.HasPrefix(host, "http://") { | |
host = "http://" + host | |
} | |
targetConn, err := net.Dial("tcp", host[7:]) | |
if err != nil { | |
log.Println("Failed to connect to target:", err) | |
return | |
} | |
defer targetConn.Close() | |
// Forward the request to the target server | |
fmt.Fprintf(targetConn, "%s", requestLine) | |
go io.Copy(targetConn, reader) | |
// Forward the response back to the client | |
io.Copy(clientConn, targetConn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment