liveBook · Manning

Timeout

As explained in 100 Go Mistakes and How to Avoid Them

A timeout is the termination or failure of an operation after it has waited longer than an allowed duration.

A timeout ends or fails an operation after it waits beyond an allowed duration. A common mistake is using http.Get or an empty http.Client in production: the default client has no timeout, so a request can wait indefinitely and exhaust resources. section 10.7.1

Match the timeout to the HTTP operation being bounded:

  • net.Dialer.Timeout limits establishing the TCP connection. section 10.7.1
  • http.Transport.TLSHandshakeTimeout limits the TLS handshake. section 10.7.1
  • http.Transport.ResponseHeaderTimeout limits waiting for response headers. section 10.7.1
  • http.Client.Timeout bounds the complete request, from dialing through reading the response body. section 10.7.1

Bound both stages and the whole request

client := &http.Client{ Timeout: 5 * time.Second, Transport: &http.Transport{ DialContext: (&net.Dialer{ Timeout: time.Second, }).DialContext, TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: time.Second, }, } section 10.7.1

Timeouts also arrive through context cancellation. A context-aware function should use select around channel sends and receives, returning ctx.Err() when cancellation or a deadline occurs instead of remaining blocked. section 8.6.4

client := &http.Client{
    Timeout: 5 * time.Second,                  #1
    Transport: &http.Transport{
        DialContext: (&net.Dialer{
            Timeout: time.Second,              #2
        }).DialContext,
        TLSHandshakeTimeout:   time.Second,    #3
        ResponseHeaderTimeout: time.Second,    #4
    },
}

Inspect a complete client configuration that combines a global request timeout with dial, TLS, and response-header limits. section 10.7.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Distinguishes four HTTP timeout scopes and cancellation behavior, but does not develop broader timeout policy.
Examples
Uses default http.Get, layered client configuration, a header-timeout error, and select-based channel operations.
What it assumes
Assumes familiarity with Go HTTP clients, channels, select, and context APIs rather than teaching their basic syntax.
What you can do after
Configure Go HTTP timeout layers and diagnose blocked channel operations through context cancellation.
How it connects
Connects HTTP clients, TCP dialing, TLS handshakes, response headers, request bodies, contexts, deadlines, and channels.

Also explained in

Compare how 9 books explain timeout →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.