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