-
Notifications
You must be signed in to change notification settings - Fork 62
/
ws-tcp-relay.go
85 lines (68 loc) · 1.68 KB
/
ws-tcp-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
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
83
84
85
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"golang.org/x/net/websocket"
)
var tcpAddress string
var binaryMode bool
func copyWorker(dst io.Writer, src io.Reader, doneCh chan<- bool) {
io.Copy(dst, src)
doneCh <- true
}
func relayHandler(ws *websocket.Conn) {
conn, err := net.Dial("tcp", tcpAddress)
if err != nil {
log.Printf("[ERROR] %v \n", err)
return
}
if binaryMode {
ws.PayloadType = websocket.BinaryFrame
}
doneCh := make(chan bool)
go copyWorker(conn, ws, doneCh)
go copyWorker(ws, conn, doneCh)
<-doneCh
conn.Close()
ws.Close()
<-doneCh
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s <tcpTargetAddress>\n", os.Args[0])
flag.PrintDefaults()
}
func main() {
var port uint
var certFile string
var keyFile string
flag.UintVar(&port, "p", 4223, "The port to listen on")
flag.UintVar(&port, "port", 4223, "The port to listen on")
flag.StringVar(&certFile, "tlscert", "", "TLS cert file path")
flag.StringVar(&keyFile, "tlskey", "", "TLS key file path")
flag.BoolVar(&binaryMode, "b", false, "Use binary frames instead of text frames")
flag.BoolVar(&binaryMode, "binary", false, "Use binary frames instead of text frames")
flag.Usage = usage
flag.Parse()
tcpAddress = flag.Arg(0)
if tcpAddress == "" {
fmt.Fprintln(os.Stderr, "No address specified")
os.Exit(1)
}
portString := fmt.Sprintf(":%d", port)
log.Printf("[INFO] Listening on %s\n", portString)
http.Handle("/", websocket.Handler(relayHandler))
var err error
if certFile != "" && keyFile != "" {
err = http.ListenAndServeTLS(portString, certFile, keyFile, nil)
} else {
err = http.ListenAndServe(portString, nil)
}
if err != nil {
log.Fatal(err)
}
}