Understanding Go’s Context Type
Understand the context package in Go and its usage.
Go provides a package called context
that is useful for two purposes, as outlined here:
-
Canceling a chain of function calls after some event (such as a timeout)
-
Passing information through a chain of function calls (such as user information)
A Context
object is usually created in either main()
or at the point of ingestion of some request (such as an RPC or HyperText Transfer Protocol (HTTP) request).
A basic Context
object is created from our background Context
object, as follows:
import "context"func main() {ctx := context.Background()}
The context
package and the Context
type is an advanced subject, but we introduce it here as it is used throughout the Go ecosystem.
Using a Context to signal a timeout
Context
is often used to communicate a timer state or to terminate a wait condition, for example, when our program is waiting for a network response.
Let's say we want to call a function to get some data, but we don't want to wait longer than 5 seconds for the call to complete. We can signal this via a Context
, as follows:
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)data, err := GatherData(ctx, args)cancel()if err != nil {return err}
context.WithTimeout()
creates a new Context
that will automatically be canceled after 5 seconds and a function that will cancel the Context (context.CancelFunc)
when called.
Every Context
is said to be derived from another Context
. Here, we derive our ctx
object from context.Background()
. The context.Background()
is our parent Context
. New context
objects can be derived from ...