-
Notifications
You must be signed in to change notification settings - Fork 5
/
relay.go
57 lines (49 loc) · 1.1 KB
/
relay.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
package main
import (
"fmt"
"log"
"net"
"os"
)
func NewRelay(bind string, server string) error {
// Listen for incoming connections.
l, err := net.Listen("tcp", bind)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
return err
}
// Handle connections in a new goroutine.
go handleRequest(conn, server)
}
}
// Handles incoming requests.
func handleRequest(conn net.Conn, server string) {
client, err := net.Dial("tcp", server)
if err != nil {
log.Printf("Dial failed: %v", err)
defer conn.Close()
return
}
log.Printf("Forwarding from %v to %v\n", conn.LocalAddr(), client.RemoteAddr())
errCh := make(chan error, 2)
// upload path
go func() { errCh <- Copy(client, conn) }()
// download path
go func() { errCh <- Copy(conn, client) }()
// Wait
err = <-errCh
if err != nil {
fmt.Println("transport error:", err)
}
client.Close()
conn.Close()
}