Timing out HTTP connections
This section presents techniques for timing out HTTP connections that take too long to finish and work either on the server or the client side.
Using SetDeadline()
The SetDeadline()
function is used by net
to set the read and write deadlines of network connections. Due to the way that SetDeadline()
works, you need to call SetDeadline()
before any read or write operation. Keep in mind that Go uses deadlines to implement timeouts, so you do not need to reset the timeout every time your application receives or sends any data.
The use of SetDeadline()
is illustrated in withDeadline.go
and, more specifically, in the implementation of the Timeout()
function:
var timeout = time.Duration(time.Second)
func Timeout(network, host string) (net.Conn, error) {
conn, err := net.DialTimeout(network, host, timeout)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(timeout))
return conn, nil
}
The timeout
...