Context Basics in Go
Server work often needs to stop when a client disconnects, a request times out, or work is no longer needed. In this Go Byte, you will learn what context.Context is, how cancellation and timeouts work, and how request context fits into HTTP handlers. What You'll Learn: - What a context carries: cancellation, deadlines or timeouts, and request-scoped data - How Done works and how waiting on it detects cancellation - How WithCancel, WithTimeout, and WithDeadline create derived contexts from a parent - How r.Context ties cancellation to the HTTP request lifecycle - When context values are appropriate and why they are used sparingly Conceptual Explanation: A context is passed between functions so one part of the program can signal another to stop. When a context is cancelled, its Done channel is closed, which unblocks code waiting on it. WithCancel returns a cancel function you can call to cancel immediately. WithTimeout and WithDeadline cancel automatically when time runs out. Background provides a root parent with no cancellation. Child contexts inherit cancellation from their parent chain. In net/http, the request context is cancelled when the client disconnects or the request ends, so long work should respect that context. How It Fits: Context is standard in Go for controlling goroutines and request-scoped work, especially after you are comfortable with HTTP handlers. It connects naturally to later patterns where you wait on multiple signals at once. For now the lesson stays focused on Done, WithCancel, WithTimeout, and passing context into functions. Key Takeaways: - Context mainly controls cancellation and time limits for ongoing work - Done closes when the context is cancelled; waiting on Done blocks until then - WithCancel, WithTimeout, and WithDeadline build derived contexts from a parent - defer cancel is good practice to release resources - r.Context is the request context in HTTP handlers - Use WithValue sparingly for request-scoped metadata only Try the challenge from the video before checking the solution. Links: Lesson folder on GitHub: https://github.com/GaryClarke/go-bytes/tree/main/context-basics Build your first Go app with me: https://www.garyclarke.tech/p/build-your-first-go-app Join the mailing list for new lessons and resources: https://content.garyclarke.tech/go-bytes-signup Follow on X/Twitter: https://twitter.com/garyclarketech Connect on LinkedIn: https://www.linkedin.com/in/garyclarketech/ Subscribe for more Go lessons. #golang #go #programming #coding #learnprogramming #gobytes
Download
1 formatsVideo Formats
Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.