2015-07-25 04:35:07 -04:00
|
|
|
// Package timeoutconn provides overridden net.Conn that supports deadline (timeout).
|
2015-02-25 14:52:37 -05:00
|
|
|
package timeoutconn
|
2014-05-23 02:58:56 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
// New creates a net.Conn with a timeout for every Read operation.
|
2015-02-25 10:59:29 -05:00
|
|
|
func New(netConn net.Conn, timeout time.Duration) net.Conn {
|
|
|
|
return &conn{netConn, timeout}
|
2014-05-23 02:58:56 -04:00
|
|
|
}
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
// A net.Conn that sets a deadline for every Read operation.
|
|
|
|
// FIXME was documented the deadline was on Write operation too but not implement
|
2015-02-25 10:59:29 -05:00
|
|
|
type conn struct {
|
2014-05-23 02:58:56 -04:00
|
|
|
net.Conn
|
|
|
|
timeout time.Duration
|
|
|
|
}
|
|
|
|
|
2015-02-25 10:59:29 -05:00
|
|
|
func (c *conn) Read(b []byte) (int, error) {
|
2014-05-23 02:58:56 -04:00
|
|
|
if c.timeout > 0 {
|
2015-04-26 12:50:25 -04:00
|
|
|
if err := c.Conn.SetReadDeadline(time.Now().Add(c.timeout)); err != nil {
|
2014-05-23 02:58:56 -04:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.Conn.Read(b)
|
|
|
|
}
|