-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_store.go
52 lines (44 loc) · 920 Bytes
/
client_store.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
package pts
import (
"github.com/google/uuid"
"sync"
)
type ClientStore struct {
clients map[string]*Client
mutex sync.RWMutex
}
func (c *ClientStore) init() {
c.clients = map[string]*Client{}
}
func (c *ClientStore) NextId() string {
var uuidGen, _ = uuid.NewRandom()
uuidString := uuidGen.String()
if _, ok := c.clients[uuidString]; ok {
return c.NextId()
}
return uuidString
}
func (c *ClientStore) Join(client *Client) {
c.mutex.Lock()
defer c.mutex.Unlock()
if client.Id == "" {
client.Id = c.NextId()
}
c.clients[client.Id] = client
}
func (c *ClientStore) Exists(id string) bool {
c.mutex.Lock()
defer c.mutex.Unlock()
_, exists := c.clients[id]
return exists
}
func (c *ClientStore) Get(id string) *Client {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.clients[id]
}
func (c *ClientStore) Remove(id string) {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.clients, id)
}