/
websocket.go
173 lines (152 loc) · 3.37 KB
/
websocket.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"gopkg.in/urfave/cli.v1"
)
type cmdWS struct{}
func (self *cmdWS) Action(c *cli.Context) error {
if c.NArg() == 0 {
return cli.NewExitError("no channelIds", 128)
}
channelIds := make([]string, c.NArg())
for i := 0; i < c.NArg(); i++ {
channelIds[i] = c.Args().Get(i)
}
log.Debugf("Subscribing %v", channelIds)
config, err := newAppConfigFrom(c.GlobalString("c"))
if err != nil {
return err
}
u := self.createUrl(c)
log.Debugf("Connecting %s", u.String())
ws, resp, err := websocket.DefaultDialer.Dial(u.String(), http.Header{
"X-Access-Token": []string{config.Token},
})
if err != nil {
return err
}
defer resp.Body.Close()
defer ws.Close()
if c.Bool("debug") {
b, err := httputil.DumpResponse(resp, true)
if err != nil {
return err
}
fmt.Fprintln(c.App.ErrWriter, string(b))
}
return self.loop(c.App.Writer, ws, channelIds)
}
type cableEvent struct {
Type string `json:"type,omitempty"`
Message *json.RawMessage `json:"message,omitempty"`
Identifier string `json:"identifier,omitempty"`
}
type cableCommand struct {
Command string `json:"command"`
Data string `json:"data,omitempty"`
Identifier string `json:"identifier"`
}
func (self *cmdWS) debugDumpJson(tag string, v interface{}) {
b, err := json.Marshal(v)
if err != nil {
log.Panic(err)
}
log.Debugf("%s %s", tag, string(b))
}
func (self *cmdWS) loop(w io.Writer, ws *websocket.Conn, channelIds []string) error {
for {
mt, r, err := ws.NextReader()
if err != nil {
log.Infof("connection was closed: %s", err)
return nil
} else if mt != websocket.TextMessage {
log.Errorf("received frame is not a text frame (%v)", mt)
continue
}
evt := &cableEvent{}
if err := json.NewDecoder(r).Decode(evt); err != nil {
log.Errorf("received a invalid message: %s", err)
continue
}
self.debugDumpJson("IN", evt)
switch evt.Type {
case "welcome":
msg := &cableCommand{
Command: "subscribe",
Identifier: `{"channel":"ChatChannel"}`,
}
self.debugDumpJson("OUT", msg)
err := ws.WriteJSON(msg)
if err != nil {
return err
}
case "confirm_subscription":
// subscribe channels
msg := &cableCommand{
Command: "message",
Identifier: `{"channel":"ChatChannel"}`,
}
dataBytes, err := json.Marshal(map[string]interface{}{
"channels": channelIds,
"action": "subscribe",
})
if err != nil {
log.Panic(err)
}
msg.Data = string(dataBytes)
self.debugDumpJson("OUT", msg)
err = ws.WriteJSON(msg)
if err != nil {
return err
}
case "":
if evt.Message == nil {
continue
}
if err := json.NewEncoder(w).Encode(evt.Message); err != nil {
return err
}
}
}
}
func (self *cmdWS) createUrl(c *cli.Context) *url.URL {
u := &url.URL{
Host: c.String("host"),
Path: c.String("path"),
}
u.Scheme = "wss"
if c.Bool("insecure") {
u.Scheme = "ws"
}
return u
}
func init() {
cmd := &cmdWS{}
commands = append(commands, cli.Command{
Name: "websocket",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "insecure",
},
&cli.StringFlag{
Name: "host",
Value: "kokoro.io",
},
&cli.StringFlag{
Name: "path",
Value: "/cable",
},
&cli.BoolFlag{
Name: "debug",
},
},
Action: cmd.Action,
})
}