-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (74 loc) · 1.73 KB
/
client.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
package nym
import (
"fmt"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"os"
"time"
)
type Client struct {
server string
conn *websocket.Conn
messages chan Response
}
func NewClient(server string) *Client {
return &Client{
server: server,
messages: make(chan Response, 1),
}
}
func (c *Client) Dial() (err error) {
c.conn, _, err = websocket.DefaultDialer.Dial(c.server, nil)
if err != nil {
return errors.Wrapf(err, "websocket.DefaultDialer.Dial %s", c.server)
}
return nil
}
func (c *Client) ListenAndServe() error {
defer close(c.messages)
for {
messageType, r, err := c.conn.NextReader()
if err != nil {
return err
}
switch messageType {
case websocket.TextMessage:
packet, err := FromJSON(r)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrap(err, ""))
continue
}
c.messages <- packet
case websocket.BinaryMessage:
fmt.Fprintln(os.Stderr, ErrBinaryMessageNotSupported)
}
}
}
func (c *Client) Close() error {
if c.conn != nil {
message := websocket.FormatCloseMessage(websocket.CloseMessage, "")
if err := c.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(10*time.Second)); err != nil {
return err
}
}
return nil
}
func (c *Client) Messages() <-chan Response {
return c.messages
}
func (c *Client) SendRequestAsText(r Request) error {
if c.conn != nil {
data, err := r.ToJSON()
if err != nil {
return errors.Wrap(err, "ToJSON")
}
if err := c.conn.WriteMessage(websocket.TextMessage, data); err != nil {
return errors.Wrapf(err, "conn.WriteMessage(websocket.TextMessage, %s)", string(data))
}
return nil
}
return ErrConnectionNotEstablished
}
func (c *Client) SendRequestAsBinary(r Request) error {
panic("implement!")
}