forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
50 lines (42 loc) · 1.01 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package tcp
import (
"io"
"net"
"github.com/containous/traefik/log"
)
// Proxy forwards a TCP request to a TCP service
type Proxy struct {
target *net.TCPAddr
}
// NewProxy creates a new Proxy
func NewProxy(address string) (*Proxy, error) {
tcpAddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
return &Proxy{
target: tcpAddr,
}, nil
}
// ServeTCP forwards the connection to a service
func (p *Proxy) ServeTCP(conn net.Conn) {
log.Debugf("Handling connection from %s", conn.RemoteAddr())
defer conn.Close()
connBackend, err := net.DialTCP("tcp", nil, p.target)
if err != nil {
log.Errorf("Error while connection to backend: %v", err)
return
}
defer connBackend.Close()
errChan := make(chan error, 1)
go connCopy(conn, connBackend, errChan)
go connCopy(connBackend, conn, errChan)
err = <-errChan
if err != nil {
log.Errorf("Error during connection: %v", err)
}
}
func connCopy(dst, src net.Conn, errCh chan error) {
_, err := io.Copy(dst, src)
errCh <- err
}