-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
116 lines (103 loc) · 2.25 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"bufio"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"golang.org/x/net/websocket"
)
type headers []string
func (h *headers) String() string {
return strings.Join(*h, ", ")
}
func (h *headers) Set(value string) error {
*h = append(*h, value)
return nil
}
func main() {
var (
target = flag.String("u", "", "The URL to connect to")
origin = flag.String("o", "", "The origin to use in the WS request")
h headers
origURL *url.URL
)
flag.Var(&h, "H", `Headers to use in the WS request, can be used to multiple times to specify multiple headers.`+
` Example: -H "Sample-Header-1: foo" -H "Sample-Header-2: bar"`)
flag.Parse()
if *target == "" {
fmt.Fprintf(os.Stderr, "missing url\n")
os.Exit(1)
}
if *origin != "" {
var err error
origURL, err = url.Parse(*origin)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse origin URL: %s", err.Error())
os.Exit(1)
}
}
ws := connect(*target, makeHeader(h), origURL)
trapCtrlC(ws)
go write(ws)
read(ws)
}
func makeHeader(h headers) http.Header {
httpH := make(http.Header)
for _, hv := range h {
splits := strings.SplitN(hv, ":", 2)
httpH.Add(strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1]))
}
return httpH
}
func connect(addr string, h http.Header, origin *url.URL) *websocket.Conn {
log.Printf("connecting to %s...", addr)
conf, err := websocket.NewConfig(addr, addr)
if err != nil {
log.Fatal(err)
}
conf.Header = h
conf.Origin = origin
ws, err := websocket.DialConfig(conf)
if err != nil {
log.Fatal(err)
}
log.Print("ready, exit with CTRL+C.")
return ws
}
// Graceful shutdown
func trapCtrlC(c *websocket.Conn) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
for range ch {
fmt.Println("\nexiting")
c.Close()
os.Exit(0)
}
}()
}
// Send STDIN lines to websocket server.
func write(ws *websocket.Conn) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
t := scanner.Text()
ws.Write([]byte(t))
fmt.Printf(">> %s\n", t)
}
}
// Read from websocket and print messages to STDOUT
func read(ws *websocket.Conn) {
msg := make([]byte, 16384)
for {
n, err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("<< %s\n", msg[:n])
}
}