2015-02-25 19:52:37 +00:00
|
|
|
package timeoutconn
|
2015-02-25 15:59:29 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func New(netConn net.Conn, timeout time.Duration) net.Conn {
|
|
|
|
return &conn{netConn, timeout}
|
|
|
|
}
|
|
|
|
|
|
|
|
// A net.Conn that sets a deadline for every Read or Write operation
|
|
|
|
type conn struct {
|
|
|
|
net.Conn
|
|
|
|
timeout time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *conn) Read(b []byte) (int, error) {
|
|
|
|
if c.timeout > 0 {
|
2015-04-26 16:50:25 +00:00
|
|
|
if err := c.Conn.SetReadDeadline(time.Now().Add(c.timeout)); err != nil {
|
2015-02-25 15:59:29 +00:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.Conn.Read(b)
|
|
|
|
}
|