diff --git a/main.go b/main.go index 05bb4a7..36497e1 100644 --- a/main.go +++ b/main.go @@ -1,15 +1,20 @@ package main import ( + "fmt" "log" + "net/http" + "net/http/httputil" + "net/url" "os" ) func main() { - p := Server{ - Addr: os.Getenv("SOURCE_ADDR"), - Target: os.Getenv("DESTINATION_ADDR"), + url, err := url.Parse(fmt.Sprintf("http://%s", os.Getenv("DESTINATION_ADDR"))) + if err != nil { + log.Fatal(err) } - log.Panicln(p.ListenAndServe()) + proxy := httputil.NewSingleHostReverseProxy(url) + log.Fatal(http.ListenAndServe(os.Getenv("SOURCE_ADDR"), proxy)) } diff --git a/proxy.go b/proxy.go deleted file mode 100644 index 6ad1f36..0000000 --- a/proxy.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "log" - "net" -) - -type Server struct { - Addr string - Target string -} - -func (s *Server) ListenAndServe() error { - listener, err := net.Listen("tcp", s.Addr) - if err != nil { - return err - } - return s.serve(listener) -} - -func (s *Server) serve(ln net.Listener) error { - for { - conn, err := ln.Accept() - if err != nil { - log.Println(err) - continue - } - go s.handleConn(conn) - } -} - -func (s *Server) handleConn(conn net.Conn) { - rconn, err := net.Dial("tcp", s.Target) - if err != nil { - return - } - - var pipe = func(src, dst net.Conn) { - defer func() { - conn.Close() - rconn.Close() - }() - - buff := make([]byte, 65535) - for { - n, err := src.Read(buff) - if err != nil { - log.Println(err) - return - } - b := buff[:n] - - _, err = dst.Write(b) - if err != nil { - log.Println(err) - return - } - } - } - - go pipe(conn, rconn) - go pipe(rconn, conn) -}