-
Notifications
You must be signed in to change notification settings - Fork 9
/
store.go
68 lines (48 loc) · 1.12 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package bifrost
import (
"errors"
"sync"
)
var ErrConnAlreadyExist = errors.New("connection already exist in store")
var ErrConnNotExist = errors.New("connection not exist in store")
type ConnectionID string
type ConnectionStore struct {
sync.RWMutex
connMap map[ConnID]Connection
}
func NewConnectionStore() *ConnectionStore {
return &ConnectionStore{
connMap: make(map[ConnID]Connection),
}
}
func (connStore ConnectionStore) AddConnection(conn Connection) error {
connStore.Lock()
defer connStore.Unlock()
connID := conn.GetID()
_, ok := connStore.connMap[connID]
//exist
if ok {
return ErrConnAlreadyExist
}
connStore.connMap[connID] = conn
return nil
}
func (connStore ConnectionStore) DeleteConnection(connID ConnID) error {
connStore.Lock()
defer connStore.Unlock()
conn, err := connStore.GetConnection(connID)
if conn == nil {
return err
}
conn.Close()
delete(connStore.connMap, connID)
return nil
}
func (connStore ConnectionStore) GetConnection(connID ConnID) (Connection, error) {
conn, ok := connStore.connMap[connID]
//exist
if ok {
return conn, nil
}
return nil, ErrConnNotExist
}