User Tools

Site Tools


go:concurrency:timeout

WithTimeout

What is it?

`context.WithTimeout(parent, d)` creates a child context that is automatically canceled after duration `d`.

Signature: `ctx, cancel := context.WithTimeout(parent, d)`

What is it used for?

  • Time-limit outgoing HTTP requests.
  • Time-limit DB queries / RPC calls.
  • Avoid hanging forever on slow dependencies.

Example

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
 
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
resp, err := http.DefaultClient.Do(req)
_ = resp
_ = err

Notes / pitfalls

  • Always `defer cancel()` to free the timer resources.
  • If you need an absolute time, use `WithDeadline`.
  • For per-request timeouts in HTTP handlers, prefer basing on `r.Context()`.

Hard words (English)

  • duration /dʊˈreɪʃən/: khoảng thời gian
  • automatically /ˌɔːtəˈmætɪkli/: tự động
  • dependency /dɪˈpendənsi/: phụ thuộc
  • hang /hæŋ/: treo/chờ mãi
go/concurrency/timeout.txt · Last modified: by phong2018