Context in HTTP and Database Calls
Propagating context through the call chain
Context in HTTP and Database Calls is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Cancelling an HTTP request
Create a cancellable context with WithCancel, pass it to the request, and call cancel when done or when an error occurs. The client aborts the TCP connection.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)database/sql with context
All database/sql methods have *Context variants: QueryContext, ExecContext, PrepareContext. These cancel the query when the context is done.
rows, err := db.QueryContext(ctx, "SELECT id FROM users WHERE active = $1", true)
if err != nil { return err }
defer rows.Close()Checking context before query
Check the context before initiating a long query to short-circuit immediately if the request is already cancelled.
if err := ctx.Err(); err != nil {
return err // context already done
}
rows, err := db.QueryContext(ctx, ...)Context and connection pooling
When a context is cancelled mid-query, database/sql marks the connection as bad if the driver supports it, preventing a poisoned connection from returning to the pool.
gRPC and context
gRPC uses context for deadline propagation. The client sets a context deadline; the server checks it on each stream receive. Metadata is also passed via context.
resp, err := client.GetUser(ctx, &pb.GetUserRequest{Id: id})Incoming request context
The HTTP server attaches a context to each incoming request via r.Context(). This context is cancelled when the client disconnects.
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
result, err := db.QueryContext(ctx, query)
}Context in middleware chains
Middleware enriches the request context with deadlines, auth data, or trace IDs then passes the enriched request to the next handler.
Propagating context through service calls
In a microservices architecture, the trace ID from the incoming request context should be injected into all outgoing HTTP and RPC headers so distributed tracing works end-to-end.
Testing with context
In tests, use context.Background() or context.WithTimeout to prevent goroutines from leaking between test cases.
Quick Check
Which function creates an HTTP request with an attached context?
Recap: Context in HTTP and DB
Key points:
- Use http.NewRequestWithContext for outgoing HTTP calls
- database/sql *Context methods cancel queries on context done
- r.Context() on incoming requests; cancelled on client disconnect
- Propagate context (and trace ID) through all downstream calls
Frequently asked questions
Is the “Context in HTTP and Database Calls” lesson free?
Yes — the full text of “Context in HTTP and Database Calls” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Context in HTTP and Database Calls”?
Propagating context through the call chain You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Context in HTTP and Database Calls” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why context.Context Exists
- WithCancel and WithTimeout
- WithDeadline and WithValue
- Context in HTTP and Database Calls