forked from tolsen/mongonet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connchecker.go
91 lines (75 loc) · 1.89 KB
/
connchecker.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
package mongonet
import "net"
import "time"
import "crypto/tls"
type ConnChecker interface {
CheckConnection() error
CheckConnectionInterval() time.Duration // set to 0 to not check
}
type CheckedConn struct {
conn net.Conn
checker ConnChecker
}
func (c CheckedConn) Read(b []byte) (n int, err error) {
for {
interval := c.checker.CheckConnectionInterval()
if interval > 0 {
if err := c.checker.CheckConnection(); err != nil {
return n, err
}
deadline := time.Now().Add(interval)
if err = c.conn.SetReadDeadline(deadline); err != nil {
return n, err
}
}
nDelta, err := c.conn.Read(b[n:])
n += nDelta
// If a timeout occurs, the TLS connection will be corrupted, and all future writes
// will return the same error. (https://golang.org/pkg/crypto/tls/#Conn.SetDeadline)
// Therefore, always return.
if isTlsConn(c.conn) {
return n, err
}
if e, ok := err.(net.Error); !ok || !e.Timeout() {
return n, err
}
}
}
func (c CheckedConn) Write(b []byte) (n int, err error) {
for {
interval := c.checker.CheckConnectionInterval()
if interval > 0 {
if err := c.checker.CheckConnection(); err != nil {
return n, err
}
deadline := time.Now().Add(interval)
if err = c.conn.SetWriteDeadline(deadline); err != nil {
return n, err
}
}
nDelta, err := c.conn.Write(b[n:])
n += nDelta
// If a timeout occurs, the TLS connection will be corrupted, and all future writes
// will return the same error. (https://golang.org/pkg/crypto/tls/#Conn.SetDeadline)
// Therefore, always return.
if isTlsConn(c.conn) {
return n, err
}
if e, ok := err.(net.Error); !ok || !e.Timeout() {
return n, err
}
}
}
func (c CheckedConn) Close() error {
return c.conn.Close()
}
func isTlsConn(conn net.Conn) bool {
switch c := conn.(type) {
case *tls.Conn:
return true
case *Conn:
return isTlsConn(c.wrapped)
default:
return false
}
}