-
Notifications
You must be signed in to change notification settings - Fork 3
/
consumer.go
79 lines (61 loc) · 1.54 KB
/
consumer.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
package actioncable
import (
"encoding/json"
"net/url"
)
type Consumer struct {
url *url.URL
Subscriptions *Subscriptions
connection *connection
opts *ConsumerOptions
}
// Passing in nil options will cause it to create the consumer with the default options.
func CreateConsumer(url *url.URL, opts *ConsumerOptions) (*Consumer, error) {
if opts == nil {
opts = NewConsumerOptions()
}
connection := newConnection(url.String())
consumer := newConsumer(url, connection)
consumer.opts = opts
return consumer, nil
}
func newConsumer(url *url.URL, connection *connection) *Consumer {
c := &Consumer{
url: url,
connection: connection,
}
c.Subscriptions = newSubscriptions(c)
return c
}
func (c *Consumer) send(data map[string]interface{}) error {
logger.Debugf("send command: %+v", data)
if identifier, ok := data["identifier"]; ok {
copied := make(map[string]interface{})
for k, v := range data {
copied[k] = v
}
encodedIdentifer, err := json.Marshal(identifier)
copied["identifier"] = string(encodedIdentifer)
if err != nil {
logger.Errorf("failed to send: %s", err.Error())
return err
}
data = copied
}
return c.connection.send(data)
}
func (c *Consumer) Connect() {
connection := newConnection(c.url.String())
connection.consumer = c
if c.opts != nil {
if c.opts.Header() != nil {
connection.header = c.opts.Header()
}
}
connection.subscriptions = c.Subscriptions
connection.start()
c.connection = connection
}
func (c *Consumer) Disconnect() {
c.connection.stop()
}