Understanding Contexts in Go

Context is one of the critical features in Go that enables concurrency. In Go, “context” refers to a package that provides functionality for request-scoped values and cancelation signals across API boundaries.

The context package works simultaneously with Go’s concurrency model, based on the concept of goroutines. Goroutines are lightweight threads of execution that you can create and manage efficiently, making it easy to create concurrent programs in Go.

4

The Context Package

The context package provides functionality for canceling long-running functions or entire call chains. The package also helps with storing request-scoped values for access anywhere within the call chain. This feature is handy when working withAPIsor microservices, where requests may span multiple function calls and you want to cancel them or attach specific values to them.

Here’s how you can import the context package in yourGo programs.

The Golang mascot, a blue gopher, climbing a ladder superimposed on a photograph of a laptop.

Context functions take in theContextstruct type of the context package. Conventionally, you should usectxas the name of the instance variable.

Functions can return the Context struct type for other functions and operations.

context by value code result

You can create a new context with theTODOfunction of the context package. The TODO function creates a new context with the value ofcontext.Done(), a channel that will close on context cancelation. You should use it as a placeholder when you need a context but no parent contexts are suitable.

Alternatively, theBackgroundfunction creates a new context with no value and an empty Done channel.

Gopher the Go mascot

You should use the Background function as the root of a context tree.

Context With Values

The context package provides functionality for propagating values and cancelation signals. You can use the values for information from request-scoped data to cancelation signals and deadlines.

The context package also allows the creation of child context inherited from parent contexts, allowing for efficient handling of values and cancelation signals throughout a program since you can pass the context through multiple functions.

Spotify Daylist on an iPad with AirPods nearby

Here’s an example of passing context through functions with the context package.

ThevaluableContextfunction takes in a context instance and returns a context instance for the following function. The context instance is a value created with theWithValuemethod. The WithValue method takes the context instance from the function and a key-value pair.

To retrieve the data from the context, you’ll need to create a new context with theTODOorBackgroundfunction and pass the context to the function (in this case, valuableContext) and receive the context with thereceiveContextDatafunction.

The ctx variable is the context instance from the Background function. The valuableContext function takes in the ctx variable and returns the context with a value that the receiveContextData function takes in and returns the value from the key-value pair.

Context Timeouts and Deadlines

Thecontextpackage provides functionality for setting timeouts and deadlines in operations. Setting timeouts and deadlines is helpful for operations that need to catch up.

Timeouts are the duration of time an operation takes. You can set a timeout for an operation to take 4 seconds; after that, the context cancels the request.

On the other hand, a deadline defines the absolute point where an operation should cancel.

you could use theWithTimeoutmethod to set a context timeout. Here’s how you can set a 2-second timeout.

Themainfunction creates a context with a timeout of two seconds. The WithTimeout function returns a cancel function you can defer for cancelation on the exit of the main function.

You can declare deadlines with theWithDeadlinemethod. The WithDeadline method takes in a context instance and a deadline time.

ThedoSomethingfunction takes in a context, and thedeadlineTimevariable is the time before thecontextdeadline. Thectxvariable is the context with a deadline.

ThectxCancelvariable cancels the context when the context exceeds its deadline.

Best Practices for Using Contexts in Go

Avoid using contexts as global variables. Using contexts as global variables may lead to unexpected code behaviors and difficult-to-trace errors, and use context sparingly to reduce code complexity.

Finally, use contexts as signals, not guarantees. Canceling a context doesn’t guarantee that all goroutines will stop running; it’s merely a signal, and goroutines are agnostic of contexts.

Rate-limiting helps to reduce bot interference and it also secures your app. Make use of Go’s inbuilt rate package to improve your app’s security.

Goodbye sending links via other apps.

Lose your laptop without this feature, and you’ll wish you had turned it on.

It saves me hours and keeps my sanity intact.

You’ve been quoting these famous films wrong all along!

Don’t let aging hardware force you into buying expensive upgrades.

Technology Explained

PC & Mobile