forked from Kount/pq-timeouts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
99 lines (87 loc) · 1.9 KB
/
conn.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
92
93
94
95
96
97
98
99
package pqtimeouts
import (
"fmt"
"net"
"time"
)
type nilConnErr struct {
}
func (e nilConnErr) Error() string {
return "Connection is nil"
}
type timeoutConn struct {
conn net.Conn
readTimeout time.Duration
writeTimeout time.Duration
}
func (t *timeoutConn) Read(b []byte) (n int, err error) {
if t.conn != nil {
if t.readTimeout != 0 {
// Set a read deadline before we call read.
t.conn.SetReadDeadline(time.Now().Add(t.readTimeout))
}
n, err = t.conn.Read(b)
if t.readTimeout != 0 {
// Clear the deadline if we have one set
t.conn.SetReadDeadline(time.Time{})
}
return
}
return 0, nilConnErr{}
}
func (t *timeoutConn) Write(b []byte) (n int, err error) {
if t.conn != nil {
if t.writeTimeout != 0 {
// Set a write deadline before we call write.
t.conn.SetWriteDeadline(time.Now().Add(t.writeTimeout))
}
n, err = t.conn.Write(b)
if t.writeTimeout != 0 {
// Clear the deadline if we have one set
t.conn.SetWriteDeadline(time.Time{})
}
return
}
return 0, nilConnErr{}
}
func (t *timeoutConn) Close() (err error) {
if t.conn != nil {
err = t.conn.Close()
if err == nil {
// If the close looked successful, set the connection to nil
t.conn = nil
}
return
}
return nilConnErr{}
}
func (t *timeoutConn) LocalAddr() net.Addr {
if t.conn != nil {
return t.conn.LocalAddr()
}
return nil
}
func (t *timeoutConn) RemoteAddr() net.Addr {
if t.conn != nil {
return t.conn.RemoteAddr()
}
return nil
}
func (t *timeoutConn) SetDeadline(time time.Time) error {
if t.conn != nil {
return t.conn.SetDeadline(time)
}
return nilConnErr{}
}
func (t *timeoutConn) SetReadDeadline(time time.Time) error {
if t.conn != nil {
return t.conn.SetReadDeadline(time)
}
return nilConnErr{}
}
func (t *timeoutConn) SetWriteDeadline(time time.Time) error {
if t.conn != nil {
return t.conn.SetWriteDeadline(time)
}
return fmt.Errorf("Connection is nil")
}