-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolConn.go
More file actions
44 lines (38 loc) · 770 Bytes
/
PoolConn.go
File metadata and controls
44 lines (38 loc) · 770 Bytes
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
package goConnectPool
import (
"net"
"sync"
)
// PoolConn is a wrapper of net.Conn to change the default Close() method.
type PoolConn struct {
net.Conn
mu sync.Mutex
c *channelPool
unusable bool
}
// Close method, return the resource back into pool is possible.
func (p *PoolConn) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.unusable {
if p.Conn != nil {
// close the conn
// actives minus one when close the connection
<-p.c.actives
return p.Conn.Close()
}
return nil
}
return p.c.put(p.Conn)
}
func (p *PoolConn) setUnusable() {
p.mu.Lock()
defer p.mu.Unlock()
p.unusable = true
}
// Wrapper function
func (c *channelPool) wrapConn(conn net.Conn) net.Conn {
p := &PoolConn{c: c}
p.Conn = conn
return p
}