Skip to content

Instantly share code, notes, and snippets.

@qhwa
Last active March 27, 2024 13:17
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save qhwa/cb9d3851450bff3b705e to your computer and use it in GitHub Desktop.
Save qhwa/cb9d3851450bff3b705e to your computer and use it in GitHub Desktop.
network port forwarding in go lang
package main
import (
"fmt"
"io"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
fmt.Println("new client")
proxy, err := net.Dial("tcp", "127.0.0.1:80")
if err != nil {
panic(err)
}
fmt.Println("proxy connected")
go copyIO(conn, proxy)
go copyIO(proxy, conn)
}
func copyIO(src, dest net.Conn) {
defer src.Close()
defer dest.Close()
io.Copy(src, dest)
}
@qhwa
Copy link
Author

qhwa commented Jan 5, 2016

This go app forwards datas from localhost:8080 to localhost:80

@masbur
Copy link

masbur commented Jul 24, 2022

Hi @qhwa

Great concept.
I have a question, how to capture request and response header ?
I want to check that header and then split into several destinations.
For example:

  • header contains "websocket" dial to localhost port 8880
  • header contains "cloudflare" dial to localhost port 8000
  • etc.

@qhwa
Copy link
Author

qhwa commented Jul 24, 2022

Hi @masbur

I think other than a simple port-forwarding, what you want is a reverse proxy. In that case, there are some resources, such as this and this on top of reverseproxy.go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment