-
Notifications
You must be signed in to change notification settings - Fork 5
/
connectionPool.go
68 lines (58 loc) · 1.25 KB
/
connectionPool.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 main
import (
"context"
"io"
"net"
)
type ConnectionPool struct {
cache *Cache
}
type Request struct {
id string // A unique id to identify a connection
network NetworkType
ctx context.Context
writer io.Writer
reader io.Reader
closeSignal chan error
}
type ServerConnection struct {
id string // A unique id to identify a connection
conn net.Conn
}
func NewConnectionPool() *ConnectionPool {
return &ConnectionPool{
NewCache(0),
}
}
func (cp *ConnectionPool) NewConnection(t NetworkType, closeSignal chan error, ctx context.Context, writer io.Writer, reader io.Reader) string {
cID := NewUUID()
cp.cache.Set(cID, Request{
cID,
t,
ctx,
writer,
reader,
closeSignal,
})
return cID
}
func (cp *ConnectionPool) NewSrvConnection(id string, conn net.Conn) {
cp.cache.Set(id, ServerConnection{
id,
conn,
})
}
func (cp *ConnectionPool) GetConnection(cID string) (Request, bool) {
c, found := cp.cache.Get(cID)
return c.(Request), found
}
func (cp *ConnectionPool) GetSrvConnection(cID string) (net.Conn, bool) {
c, found := cp.cache.Get(cID)
if !found {
return nil, false
}
return c.(ServerConnection).conn, found
}
func (cp *ConnectionPool) RmConnection(cID string) {
cp.cache.Delete(cID)
}