timeoutconn.go 479 B

1234567891011121314151617181920212223242526
  1. package utils
  2. import (
  3. "net"
  4. "time"
  5. )
  6. func NewTimeoutConn(conn net.Conn, timeout time.Duration) net.Conn {
  7. return &TimeoutConn{conn, timeout}
  8. }
  9. // A net.Conn that sets a deadline for every Read or Write operation
  10. type TimeoutConn struct {
  11. net.Conn
  12. timeout time.Duration
  13. }
  14. func (c *TimeoutConn) Read(b []byte) (int, error) {
  15. if c.timeout > 0 {
  16. err := c.Conn.SetReadDeadline(time.Now().Add(c.timeout))
  17. if err != nil {
  18. return 0, err
  19. }
  20. }
  21. return c.Conn.Read(b)
  22. }