Skip to content

Go Context: HTTP Request Cancellation

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Context: HTTP Request Cancellation. We cover key concepts, practical examples, and best practices.

HTTP request with context -- Use http.NewRequestWithContext to create cancellable HTTP requests.

The Problem

http.Get and http.Post do not accept contexts. Use http.NewRequestWithContext to create requests that respect cancellation.

Wrong

resp, err := http.Get("https://api.example.com/data")

Output:

// No context. Request cannot be cancelled or timeout.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
if err != nil { log.Fatal(err) }
resp, err := http.DefaultClient.Do(req)

Output:

// Request cancelled after 5 seconds or when context is done

Prevention

  • Use NewRequestWithContext for cancellable HTTP
  • Combine with http.Client timeout for defense in depth
  • Context cancels the request body download
  • Pass context through the call chain
  • Check resp.Body.Close() honours context for streaming

Common Mistakes with context http request

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does http.Get support context?**

No. Use NewRequestWithContext + Client.Do().

What happens when context is cancelled mid-request?

The in-flight request is terminated.

Can I set both context timeout and Client.Timeout?

Yes. The shorter one wins.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro