Skip to Content
Learning Go, 2nd Edition
book

Learning Go, 2nd Edition

by Jon Bodner
January 2024
Beginner
494 pages
12h 30m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Go, 2nd Edition

Chapter 14. The Context

Servers need a way to handle metadata on individual requests. This metadata falls into two general categories: metadata that is required to correctly process the request, and metadata on when to stop processing the request. For example, an HTTP server might want to use a tracking ID to identify a chain of requests through a set of microservices. It also might want to set a timer that ends requests to other microservices if they take too long.

Many languages use threadlocal variables to store this kind of information, associating data to a specific operating system thread of execution. This doesn’t work in Go because goroutines don’t have unique identities that can be used to look up values. More importantly, threadlocals feel like magic; values go in one place and pop up somewhere else.

Go solves the request metadata problem with a construct called the context. Let’s see how to use it correctly.

What Is the Context?

Rather than add a new feature to the language, a context is simply an instance that meets the Context interface defined in the context package. As you know, idiomatic Go encourages explicit data passing via function parameters. The same is true for the context. It is just another parameter to your function.

Just as Go has a convention that the last return value from a function is an error, Go has another convention that the context is explicitly passed through your program as the first parameter of a function. The usual name for the context ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Designing Data-Intensive Applications, 2nd Edition

Designing Data-Intensive Applications, 2nd Edition

Martin Kleppmann, Chris Riccomini

Publisher Resources

ISBN: 9781098139285Errata PageSupplemental Content