Contexts in Go
Contexts are a fundamental concept in Go. They provide a way to pass deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
What is a Context?
A context is an interface type that represents a request-scoped environment. It contains values that are shared across all functions that are involved in handling a request. These values can include:
- Deadlines
- Cancellation signals
- Request-specific data (e.g., user ID, session ID)
Creating Contexts
Contexts are typically created using the context.Background()
function. This function creates a new context that is not associated with any request. You can also create a context from an existing context using the context.WithXXX()
functions. For example, the context.WithTimeout()
function creates a new context that expires after a specified duration.
Using Contexts
Contexts are passed as arguments to functions that need to access request-scoped values. For example, the http.Handler
interface defines a method called ServeHTTP()
that takes a context as an argument. This context can be used to access the request deadline, cancellation signal, and other request-specific data.
Context Deadlines
One of the most important uses of contexts is to enforce deadlines for API operations. The context.WithTimeout()
function can be used to create a new context that expires after the specified amount of time. If a function that is passed a context does not complete before the deadline, it will be cancelled.
Context Cancellation
Contexts can also be cancelled. This can be useful when a request is no longer needed. The context.CancelFunc()
function returns a function that can be called to cancel the context. When a context is cancelled, all of the functions that are waiting on it will be interrupted.
Context Values
Contexts can store arbitrary values that can be accessed by functions that are passed the context. This can be useful for storing request-specific data that needs to be shared across API boundaries. The context.WithValue()
function can be used to set a value on a context. The context.Value()
function can be used to retrieve a value from a context.
Conclusion
Contexts are a powerful tool for managing request-scoped values in Go. They can be used to enforce deadlines, handle cancellations, and store request-specific data.
Kind regards R. Morris.