-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnector.go
68 lines (58 loc) · 1.57 KB
/
connector.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
package pts
import (
"net/http"
)
type ConnectHookFunc func(*Client)
type DisconnectHookFunc func(*Client)
type MessageHookFunc func(*Client, []byte)
type RequestHandlerFunc func(writer http.ResponseWriter, request *http.Request, properties map[string]interface{}) error
type Connector struct {
requestHandler RequestHandlerFunc
errorHandler ErrorHandlerFunc
clients ClientStore
hooks *Hooks
}
type Hooks struct {
OnConnect ConnectHookFunc
OnDisconnect DisconnectHookFunc
OnMessage MessageHookFunc
}
func NewConnector(requestHandler RequestHandlerFunc, errorHandler ErrorHandlerFunc) *Connector {
connector := &Connector{
requestHandler: requestHandler,
hooks: &Hooks{},
errorHandler: errorHandler,
}
connector.clients.init()
return connector
}
// Join To be triggered if a client connects via ws
func (c *Connector) Join(sendMessage MessageSendFunc, properties map[string]interface{}) *Client {
client := NewClient(sendMessage, properties)
c.clients.Join(client)
if c.hooks.OnConnect != nil {
c.hooks.OnConnect(client)
}
return client
}
func (c *Connector) Message(clientId string, data []byte) {
client := c.clients.Get(clientId)
if c.hooks.OnMessage != nil {
c.hooks.OnMessage(client, data)
}
}
func (c *Connector) Leave(clientId string) {
client := c.clients.Get(clientId)
if c.hooks.OnDisconnect != nil {
c.hooks.OnDisconnect(client)
}
c.clients.Remove(client.Id)
}
func (c *Connector) error(err *Error) {
if c.errorHandler != nil {
c.errorHandler(err)
}
}
func (c *Connector) hook(hooks *Hooks) {
c.hooks = hooks
}