Last active
August 7, 2019 10:30
-
-
Save anjmao/8d49808f0015b98bed05a95e90c11b17 to your computer and use it in GitHub Desktop.
Simplest Go TCP proxy
This file contains 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 ( | |
"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