Dark Hydra
Dark Hydra

Reputation: 275

HTTP client, idle timeout

How to make idle timeout in Go HTTP client?

Idle timeout means timeout on calling Read/Write methods of Conn interface from HTTP client internals. It can be useful when client downloads file and in some moment downloading fails because read timeout reached.

Upvotes: 0

Views: 2165

Answers (1)

JimB
JimB

Reputation: 109325

You need to create your own net.Dialer, that returns a net.Conn which sets the appropriate read and write deadlines.

The Conn would look something like this:

// 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)
}

Upvotes: 1

Related Questions