-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrewindconn.go
61 lines (52 loc) · 1.06 KB
/
rewindconn.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 caddy_clienthello
// Obtained from https://github.com/gaukas/clienthellod/blob/7cce34b88b314256c8759998f6192860f6f6ede5/internal/utils/rewindconn.go
import (
"bytes"
"errors"
"io"
"net"
)
type rewindConn struct {
net.Conn
reader bytes.Reader
}
func RewindConn(c net.Conn, buf []byte) (net.Conn, error) {
if c == nil {
return nil, errors.New("cannot rewind nil connection")
}
if len(buf) == 0 {
return c, nil
}
return &rewindConn{
Conn: c,
reader: *bytes.NewReader(buf),
}, nil
}
// Read is ...
func (c *rewindConn) Read(b []byte) (int, error) {
if c.reader.Size() == 0 {
return c.Conn.Read(b)
}
n, err := c.reader.Read(b)
if errors.Is(err, io.EOF) {
c.reader.Reset([]byte{})
return n, nil
}
return n, err
}
// CloseWrite is ...
func (c *rewindConn) CloseWrite() error {
if cc, ok := c.Conn.(*net.TCPConn); ok {
return cc.CloseWrite()
}
if cw, ok := c.Conn.(interface {
CloseWrite() error
}); ok {
return cw.CloseWrite()
}
return errors.New("not supported")
}
// Interface guards
var (
_ net.Conn = (*rewindConn)(nil)
)