Skip to content

Instantly share code, notes, and snippets.

@rkravchik
Created June 19, 2018 15:42
Show Gist options
  • Select an option

  • Save rkravchik/dbfd1f5c820b97af27a85ea9668a35e9 to your computer and use it in GitHub Desktop.

Select an option

Save rkravchik/dbfd1f5c820b97af27a85ea9668a35e9 to your computer and use it in GitHub Desktop.
net.Connection with read and write timeouts.
// from https://stackoverflow.com/a/27785380
// Conn wraps a net.Conn, and sets a deadline for every read
// and write operation.
type Conn struct {
net.Conn
ReadTimeout time.Duration
WriteTimeout time.Duration
}
func (c *Conn) Read(b []byte) (int, error) {
err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
if err != nil {
return 0, err
}
return c.Conn.Read(b)
}
func (c *Conn) Write(b []byte) (int, error) {
err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
if err != nil {
return 0, err
}
return c.Conn.Write(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment