forked from dhx71/sockjs-go-client
/
client.go
92 lines (74 loc) · 1.71 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
90
91
92
package sockjsclient
import (
"encoding/json"
"net/http"
"strings"
)
type Client struct {
Connection Connection
WebSockets bool
Address string
ReadBufSize int
WriteBufSize int
Reconnected chan struct{}
RequestHeaders http.Header
Jar http.CookieJar
}
func NewClient(address string, headers http.Header, jar http.CookieJar) (*Client, error) {
client := &Client{RequestHeaders: headers, Jar: jar}
client.Address = address
// Get info whether WebSockets are enabled
info, err := client.Info()
if err != nil {
return nil, err
}
client.WebSockets = info.WebSocket
// Create a WS session (not a SJS one)
if client.WebSockets {
a2 := strings.Replace(address, "https", "wss", 1)
a2 = strings.Replace(a2, "http", "ws", 1)
ws, err := NewWebSocket(a2, headers, jar)
if err != nil {
return nil, err
}
client.Connection = ws
client.Reconnected = ws.Reconnected
} else {
// XHR
client.Connection, err = NewXHR(address)
if err != nil {
return nil, err
}
}
return client, nil
}
func (c *Client) Info() (*Info, error) {
client := http.Client{Jar: c.Jar}
req, err := http.NewRequest(http.MethodGet, c.Address+"/info", nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var info *Info
if err := dec.Decode(&info); err != nil {
return nil, err
}
return info, nil
}
func (c *Client) Write(p []byte) (int, error) {
return c.Connection.Write(p)
}
func (c *Client) Read(p []byte) (int, error) {
return c.Connection.Read(p)
}
func (c *Client) Close() error {
return c.Connection.Close()
}
func (c *Client) ForceClose() {
c.Connection.ForceClose()
}