Skip to content

Instantly share code, notes, and snippets.

@anjmao
Last active August 7, 2019 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anjmao/8d49808f0015b98bed05a95e90c11b17 to your computer and use it in GitHub Desktop.
Save anjmao/8d49808f0015b98bed05a95e90c11b17 to your computer and use it in GitHub Desktop.
Simplest Go TCP proxy
package main
import (
"flag"
"io"
"log"
"net"
)
var (
addr = flag.String("addr", ":8100", "Local proxy address")
raddr = flag.String("raddr", "localhost:10000", "Remove endpoint address")
)
func main() {
flag.Parse()
list, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatalf("cannot listen to %s: %v", *addr, err)
}
for {
conn, err := list.Accept()
if err != nil {
log.Fatalf("cannot accept conn: %v", err)
}
go proxy(conn)
}
}
// proxy proxies connection to remote service. Not that this is not production ready
// as it is missing timeouts, slow client atacks etc.
func proxy(conn net.Conn) {
log.Printf("proxy %s: %s\n", conn.LocalAddr().String(), conn.RemoteAddr().String())
remote, err := net.Dial("tcp", *raddr)
if err != nil {
log.Fatalf("cannot dial to remote: %v", err)
}
defer remote.Close()
go io.Copy(remote, conn)
io.Copy(conn, remote)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment