===== 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()`. ==== Related pages ==== * [[go:concurrency:context|context.Context]] * [[go:concurrency:withdeadline|WithDeadline]] ==== 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