-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
60 lines (48 loc) · 1.04 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
package dlm
import (
"context"
"errors"
"net"
"net/rpc"
"time"
)
func connect(ctx context.Context, addr string, timeout time.Duration) (*rpc.Client, error) {
var d = net.Dialer{
Timeout: timeout,
}
c, err := d.Dial("tcp", addr)
if err != nil {
return nil, err
}
conn := &Conn{
Conn: c,
}
conn.ctx, conn.cancel = context.WithCancel(ctx)
go conn.waitContext()
return rpc.NewClient(conn), nil
}
// Conn wrap net.Conn with context support
type Conn struct {
ctx context.Context
cancel context.CancelFunc
net.Conn
}
func (c *Conn) waitContext() {
// disabled deadline
c.Conn.SetDeadline(time.Time{}) // nolint: errcheck
<-c.ctx.Done()
err := c.ctx.Err()
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
c.Conn.SetDeadline(time.Unix(1, 0)) // nolint: errcheck
}
}
func (c *Conn) Read(p []byte) (n int, err error) {
return c.Conn.Read(p)
}
func (c *Conn) Write(p []byte) (n int, err error) {
return c.Conn.Write(p)
}
func (c *Conn) Close() error {
defer c.cancel()
return c.Conn.Close()
}