Table of Contents

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?

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

Hard words (English)