-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
95 lines (83 loc) · 2.02 KB
/
manager.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
package models
import (
"sync"
"gopkg.in/mgo.v2/bson"
)
// Manager struct, contains all the virtual clients
type Manager struct {
rw *sync.RWMutex
clients []*Client
}
// Client - Return a specific client, the index is based on in memory array
func (c Manager) Client(i int) (cl *Client) {
if i >= c.Length() {
return
}
c.rw.RLock()
defer c.rw.RUnlock()
return c.clients[i]
}
// Clients - Return all the clients
func (c Manager) Clients() (cls []*Client) {
c.rw.RLock()
defer c.rw.RUnlock()
return c.clients
}
// ClientByID - Check for a specifci client based on the client ID
func (c Manager) ClientByID(id bson.ObjectId) (cl *Client) {
for cli := range c.IterClients() {
if cli.ID() == id {
cl = cli
break
}
}
return
}
// AddClient - Add a new client to in memory array
func (c *Manager) AddClient(client *Client) {
c.rw.Lock()
defer c.rw.Unlock()
c.clients = append(c.clients, client)
}
// RemoveClient - Remove a client from memory, the index is based on in memory array
func (c *Manager) RemoveClient(i int) (ok bool) {
if i >= c.Length() || i < 0 {
return false
}
c.rw.Lock()
defer c.rw.Unlock()
c.clients = append(c.clients[:i], c.clients[i+1:]...)
return true
}
// RemoveClientByID - Remove a client from memory based on the id
func (c *Manager) RemoveClientByID(id bson.ObjectId) (ok bool) {
c.rw.Lock()
defer c.rw.Unlock()
for i := c.Length() - 1; i >= 0; i-- {
cl := c.Client(i)
if cl != nil && cl.ID() == id {
c.clients = append(c.clients[:i], c.clients[i+1:]...)
return true
}
}
return false
}
// IterClients - Will return a channel and loop through all the clients in a safe way and pass it to the channel
func (c Manager) IterClients() <-chan *Client {
ch := make(chan *Client, c.Length())
go func() {
c.rw.RLock()
defer c.rw.RUnlock()
for _, cl := range c.clients {
ch <- cl
}
close(ch)
}()
return ch
}
// Length - Will return the amount of clients in memory
func (c Manager) Length() (count int) {
c.rw.RLock()
defer c.rw.RUnlock()
return len(c.clients)
}