Hey!
My apologies for being absent for the last few weeks. I’ve been incredibly busy closing on a new house and moving.
We’re still settling, but it’s time to start this up again.
So today I’m starting a short series on context
! Specifically, I’ll be going through the context
package in the standard library, explaining what it does, and offering my advice, much like I went through the Go spec in the past.
Meanwhile, if you have any questions, about the daily mails, or any other Go-related topics, please send them my way, and I’ll try to get to them in a future daily email.
–
Overview
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
This single sentence carries a lot of weight. And probably leaves a lot of room for confusion, if you’re not already very familiar with the use of the context
package.
But we’ll have plenty of time to dive into all the nuances. For now, let me just offer a high-level explanation of the two main types of problems the context
package is meant to solve, to give you some context.
-
Cancellation signals
Imagine you’re building a web service. Probably not hard to imagine. Most of us have done this at least once. Now further imagine that your web service talks to a database. And some of those database queries take a long time to complete. Maybe up to a few seconds in some cases. Now let’s say the user of your web application clicks on the “Display past orders” page, so your service queries the database for all of the users’ past orders. Meanwhile, the user clicks away to some other page, because they really wanted to change their email address. Now your database continues chugging away at those past orders for another couple of seconds, before sending the results to… nowhere!
Enter the “cancellation signals” use case. Wouldn’t it be nice if your application could somehow be told “Hey, the user no longer wants this orders page. You can stop the work you were doing.”
context
gives us this ability. -
Request-scoped values
Let’s continue with the web application example. Let’s say that things like looking up past orders, depend on knowing a user ID, which is derrived from a cookie.
We could build your web application to do that cookie-to-user-id translation in many places, but that’s probably slow, and difficult to reason about. Instead, what if we could write a single middleware somewhere that looked up that user id once, then stored it in an easy-to-find location that all other functions could use?
Enter the “request-scoped values” use case. With
context
, you can store that user id in a request-scoped context, so that all other functions that work with the request can find the value in a convenient location.
In the coming days we’ll talk about how the context
package solves these problems, along with good and bad patterns.