Context is one of the critical features in Go that enables concurrency.

The context package works simultaneously with Go’s concurrency model, based on the concept of goroutines.

The Context Package

The context package provides functionality for canceling long-running functions or entire call chains.

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

The package also helps with storing request-scoped values for access anywhere within the call chain.

Heres how it’s possible for you to import the context package in yourGo programs.

Context functions take in theContextstruct pop in of the context package.

context by value code result

Conventionally, you should usectxas the name of the instance variable.

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

you’re free to create a new context with theTODOfunction of the context package.

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.

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 could use the values for information from request-scoped data to cancelation signals and deadlines.

Heres 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.

The ctx variable is the context instance from the Background function.

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.

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

you’re free to use theWithTimeoutmethod to set a context timeout.

Heres how you’re able to set a 2-second timeout.

Themainfunction creates a context with a timeout of two seconds.

you’re free to 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.

Finally, use contexts as signals, not guarantees.