-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_conn.go
61 lines (50 loc) · 1.41 KB
/
client_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
package sshx
import (
"context"
"errors"
"fmt"
"net"
"time"
)
type clientTCPConnWithSoftDeadline struct {
net.Conn
timeout time.Duration
}
func (c clientTCPConnWithSoftDeadline) Read(b []byte) (int, error) {
if err := c.Conn.SetReadDeadline(time.Now().Add(c.timeout)); err != nil {
return 0, fmt.Errorf("unable to set read deadline: %w", err)
}
return c.Conn.Read(b)
}
func (c clientTCPConnWithSoftDeadline) Write(b []byte) (int, error) {
if err := c.Conn.SetWriteDeadline(time.Now().Add(c.timeout)); err != nil {
return 0, fmt.Errorf("unable to set write deadline: %w", err)
}
return c.Conn.Write(b)
}
type clientTCPConnWithHardDeadline struct {
net.Conn
timeout time.Duration
}
func (c clientTCPConnWithHardDeadline) Read(b []byte) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
go func() {
<-ctx.Done()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
_ = c.Conn.Close() //nolint:errcheck // we tried, it failed, conn is broken, read will fail
}
}()
return c.Conn.Read(b)
}
func (c clientTCPConnWithHardDeadline) Write(b []byte) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
go func() {
<-ctx.Done()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
_ = c.Conn.Close() //nolint:errcheck // we tried, it failed, conn is broken, read will fail
}
}()
return c.Conn.Write(b)
}