-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
82 lines (71 loc) · 1.57 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
package main
import (
"bufio"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/gorilla/websocket"
)
var url = flag.String("url", "", "-url ws://127.0.0.1")
var headers = flag.String("headers", "", "-headers name1=value1,name2=value2")
func main() {
flag.Parse()
if *url == "" {
log.Fatal("URL can't be empty.")
}
headersMap := make(map[string]string)
if *headers != "" {
headersSeq := strings.Split(*headers, ",")
for _, headerString := range headersSeq {
splittedHeader := strings.Split(headerString, "=")
headersMap[splittedHeader[0]] = splittedHeader[1]
}
}
done := make(chan bool)
c := NewClient(*url, headersMap)
go func() {
for {
_, r, err := c.ReadMessage()
if err != nil {
log.Fatal(err)
return
}
fmt.Println("\n", color(string(r)))
}
}()
r := bufio.NewReader(os.Stdin)
go func() {
for {
line, err := r.ReadString('\n')
if err != nil && err.Error() != "unexpected newline" {
fmt.Println(err)
return
}
line = strings.TrimSpace(line)
if err = c.WriteMessage(1, []byte(line)); err != nil {
fmt.Println(err.Error())
}
}
}()
<-done
}
func NewClient(url string, headers map[string]string) *websocket.Conn {
r, _ := http.NewRequest("GET", url, nil)
r.Header.Add("Content-Type", "application/json")
for key, value := range headers {
r.Header.Add(key, value)
}
c, _, err := websocket.DefaultDialer.Dial(url, r.Header)
if err != nil {
log.Fatal("errrr ", err)
} else {
fmt.Println("Connected!")
}
return c
}
func color(msg string) string {
return ("\033[36m" + msg + "\033[0m")
}