0Pricing
Go Academy · Lesson

Context in HTTP and Database Calls

Propagating context through the call chain

HTTP client with context

Pass a context to an outgoing HTTP request using req.WithContext(ctx). The request is cancelled if the context is cancelled before the response arrives.

req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        // timeout
    }
}

http.NewRequestWithContext

Prefer http.NewRequestWithContext (Go 1.13+) over creating a request then calling WithContext — it is cleaner and avoids an intermediate allocation.

All lessons in this course

  1. Why context.Context Exists
  2. WithCancel and WithTimeout
  3. WithDeadline and WithValue
  4. Context in HTTP and Database Calls
← Back to Go Academy