Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Go TCP Proxy / Port Forwarding Example (
package main
import (
var (
target string
port int
func init() {
flag.StringVar(&target, "target", "", "the target (<host>:<port>)")
flag.IntVar(&port, "port", 7757, "the tunnelthing port")
func main() {
signals := make(chan os.Signal, 1)
stop := make(chan bool)
signal.Notify(signals, os.Interrupt)
go func() {
for _ = range signals {
fmt.Println("\nReceived an interrupt, stopping...")
stop <- true
incoming, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("could not start server on %d: %v", port, err)
fmt.Printf("server running on %d\n", port)
client, err := incoming.Accept()
if err != nil {
log.Fatal("could not accept client connection", err)
defer client.Close()
fmt.Printf("client '%v' connected!\n", client.RemoteAddr())
target, err := net.Dial("tcp", target)
if err != nil {
log.Fatal("could not connect to target", err)
defer target.Close()
fmt.Printf("connection to server %v established!\n", target.RemoteAddr())
go func() { io.Copy(target, client) }()
go func() { io.Copy(client, target) }()
Copy link

phanirithvij commented Nov 19, 2020

Hi, great concept.
But I think it's very slow for http requests, or is it not meant for HTTP requests?

I was trying to access a nodejs application which serves on port 8080, from localhost:5000
Upon inspecting, the network tab had 3 or 4 files loaded successfully but some other requests are (pending) forever.

This worked for me perfectly though

Copy link

zupzup commented Nov 19, 2020

hey @phanirithvij!

This very simple example for a blog post shouldn't be used for any real application, it's use is to show off some concepts.

The reason it doesn't work well is because it only accepts one connection (incoming.Accept), whereas the example you posted accepts in a loop and hence handles multiple connections. That's also why some files go through, and others don't in your test.

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