changed proxy

This commit is contained in:
Hendrik Schlehlein 2019-06-18 04:22:31 +02:00
parent 98ba2c9212
commit 6321b38bac
2 changed files with 9 additions and 67 deletions

13
main.go
View file

@ -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))
}

View file

@ -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)
}