-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy_tcp.go
82 lines (70 loc) · 1.6 KB
/
proxy_tcp.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"net"
"time"
"gopkg.in/eapache/go-resiliency.v1/retrier"
)
// DefaultRetrier is default retry strategy when net.Dial to the destination is failed.
var DefaultRetrier = retrier.New(retrier.ExponentialBackoff(5, 200*time.Millisecond), nil)
// TCPProxy is proxy for TCP.
type TCPProxy struct {
from string
to string
timeout time.Duration
listner net.Listener // local port server
retry *retrier.Retrier
}
// newTCPProxy creates TCPProxy with initialized local port listener.
func newTCPProxy(from, to string) (*TCPProxy, error) {
l, err := net.Listen("tcp", from)
if err != nil {
return nil, err
}
return &TCPProxy{
from: from,
to: to,
listner: l,
retry: DefaultRetrier,
}, nil
}
func (p TCPProxy) String() string {
return fmt.Sprintf("TCPProxy: %s -> %s", p.from, p.to)
}
// Close closes local port listner.
func (p *TCPProxy) Close() {
if p.listner != nil {
p.listner.Close()
}
}
// Serve serves proxy network.
func (p *TCPProxy) Serve() {
l := p.listner
for {
fromReq, err := l.Accept()
if err != nil {
loggingError("Connection from %s, %s", p.from, err.Error())
continue
}
err = p.retry.Run(func() error {
toReq, err := net.Dial("tcp", p.to)
if err != nil {
loggingError("Connection to %s, %s", p.to, err.Error())
return err
}
TCPPipe{
From: fromReq,
To: toReq,
Timeout: p.timeout,
Debug: _debug,
}.Do()
return nil
})
if err != nil {
loggingError("Give up connection to %s, %s", p.to, err.Error())
}
}
}
func (p *TCPProxy) SetTimeout(t time.Duration) {
p.timeout = t
}