-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
61 lines (51 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
61
package protomux
import (
"bytes"
"io"
"net"
)
const (
preReadBufferSize = 128
)
// Conn wraps a net.Conn for content introspection
type Conn struct {
net.Conn
buffer *bytes.Buffer
protocol Protocol
}
func wrapConn(conn net.Conn) *Conn {
return &Conn{
Conn: conn,
buffer: bytes.NewBuffer(make([]byte, 0, preReadBufferSize)),
protocol: None,
}
}
func (c *Conn) Read(b []byte) (n int, err error) {
// If the buffer is already drained, read from conn
if c.buffer == nil {
return c.Conn.Read(b)
}
n, err = c.buffer.Read(b)
// If we encounter EOF while reading,
// close the buffer and read the remaining bytes
// from the connection directly.
if err == io.EOF {
c.buffer = nil
var n2 int
n2, err = c.Conn.Read(b[n:])
n += n2
}
return
}
// Protocol returns the determined protocol.
func (c *Conn) Protocol() Protocol {
return c.protocol
}
func (c *Conn) fillBuffer() {
buf := make([]byte, preReadBufferSize)
c.Conn.Read(buf)
c.buffer.Write(buf)
}
func (c *Conn) setProtocol(newType Protocol) {
c.protocol = newType
}