This repository has been archived by the owner on Feb 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hub.go
108 lines (93 loc) · 2.18 KB
/
Hub.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
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"github.com/tidwall/gjson"
"fmt"
)
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
clients map[*Socket]bool
send chan *Message
register chan *Socket
unregister chan *Socket
handleMessage chan *SocketMessage
}
type Message struct {
clientid string
text string
}
type ClientResponse struct {
clients []ClientInformation
}
type ClientInformation struct {
id int64
accountid int64
account_email string
account_password string
script_name string
script_arguments string
}
type SocketMessage struct {
Socket *Socket
Message []byte
}
type APIRequest struct {
ApiRoute string
ApiArguments map[string]interface{}
}
type APIResponse struct {
Success bool
Result interface{}
}
var hub = newHub()
func newHub() *Hub {
return &Hub{
send: make(chan *Message),
register: make(chan *Socket),
unregister: make(chan *Socket),
clients: make(map[*Socket]bool),
handleMessage: make(chan *SocketMessage),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <- h.send:
h.sendTo(message.clientid, message.text)
case data := <- h.handleMessage:
request := gjson.GetBytes(data.Message, "Type").String()
if request == "APIRequest" {
var apiRequest APIRequest
if json.Unmarshal(data.Message, &apiRequest) == nil {
fmt.Printf("Attempting to request with data %+v", apiRequest)
if bytes, err := json.Marshal(Functions[apiRequest.ApiRoute](&apiRequest)); err == nil {
data.Socket.send <- bytes
}
}
}
}
}
}
func (h *Hub) sendTo(clientid string, message string) {
for client := range h.clients {
if client.id == clientid {
select {
case client.send <- []byte(message):
default:
close(client.send)
delete(h.clients, client)
}
}
}
}