From 6321b38bacc397a6de06a792ed9c748ccbb03a97 Mon Sep 17 00:00:00 2001 From: Hendrik Schlehlein Date: Tue, 18 Jun 2019 04:22:31 +0200 Subject: [PATCH] changed proxy --- main.go | 13 ++++++++---- proxy.go | 63 -------------------------------------------------------- 2 files changed, 9 insertions(+), 67 deletions(-) delete mode 100644 proxy.go 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) -}