redis/internal/pool/conn.go

70 lines
1.2 KiB
Go
Raw Normal View History

package pool
import (
"bufio"
"net"
"time"
)
const defaultBufSize = 4096
2016-03-12 13:41:02 +03:00
var noDeadline = time.Time{}
type Conn struct {
2016-03-12 13:41:02 +03:00
idx int
netConn net.Conn
Rd *bufio.Reader
Buf []byte
UsedAt time.Time
ReadTimeout time.Duration
WriteTimeout time.Duration
}
func NewConn(netConn net.Conn) *Conn {
cn := &Conn{
2016-03-12 13:41:02 +03:00
idx: -1,
netConn: netConn,
Buf: make([]byte, defaultBufSize),
UsedAt: time.Now(),
}
cn.Rd = bufio.NewReader(cn)
return cn
}
2016-03-12 13:41:02 +03:00
func (cn *Conn) SetNetConn(netConn net.Conn) {
cn.netConn = netConn
cn.UsedAt = time.Now()
}
func (cn *Conn) Read(b []byte) (int, error) {
cn.UsedAt = time.Now()
if cn.ReadTimeout != 0 {
2016-03-12 13:41:02 +03:00
cn.netConn.SetReadDeadline(cn.UsedAt.Add(cn.ReadTimeout))
} else {
2016-03-12 13:41:02 +03:00
cn.netConn.SetReadDeadline(noDeadline)
}
2016-03-12 13:41:02 +03:00
return cn.netConn.Read(b)
}
func (cn *Conn) Write(b []byte) (int, error) {
cn.UsedAt = time.Now()
if cn.WriteTimeout != 0 {
2016-03-12 13:41:02 +03:00
cn.netConn.SetWriteDeadline(cn.UsedAt.Add(cn.WriteTimeout))
} else {
2016-03-12 13:41:02 +03:00
cn.netConn.SetWriteDeadline(noDeadline)
}
2016-03-12 13:41:02 +03:00
return cn.netConn.Write(b)
}
func (cn *Conn) RemoteAddr() net.Addr {
2016-03-12 13:41:02 +03:00
return cn.netConn.RemoteAddr()
}
func (cn *Conn) Close() error {
2016-03-12 13:41:02 +03:00
return cn.netConn.Close()
}