Want to learn how to build better Go applications faster and easier? You can.
Check out my course on the Go Standard Library. You can check it out now for free.
In Go, the context
package provides a way to manage cancellable contexts that can be used to signal the termination of long-running operations. In this article, we’ll explore the concept of context and how it’s used in Go.
A context represents a request or operation that may need to be cancelled due to some external reason, such as a user pressing “Cancel” on their browser. It provides a way to signal the termination of long-running operations, allowing them to cleanup resources and terminate properly.
Contexts are essential in Go programming because they:
To use context in Go, you create a new context using the context.Background()
function:
ctx := context.Background()
This creates a default context that can be used as the root of your request hierarchy. You can then pass this context to functions or goroutines that need it.
Contexts support cancelation, which allows you to signal the termination of long-running operations. To cancel a context, use the ctx.Done()
method:
ctx.Done()
This sends a cancellation signal to all goroutines that are waiting on this context using the SELECT
statement.
To use context in goroutines, you can pass it as an argument to the goroutine or access it from the current context:
func process(ctx context.Context) {
for {
select {
case <-ctx.Done():
// Operation cancelled; cleanup and exit
return
default:
// Continue processing
}
}
}
In this example, the process
function checks the context’s cancellation signal using the SELECT
statement. If the context is cancelled, it cleans up and exits.
The net/http
package provides built-in support for contexts. You can create a new context for an HTTP request using the http.Context()
function:
ctx := http.Context()
This context is automatically cancelled when the request times out or is terminated by the client.
In this article, we explored the concept of context in Go and how it’s used to manage cancellable contexts. Contexts provide a way to signal the termination of long-running operations, allowing for better error handling and simplifying cancellation. In our next article, we’ll explore more advanced concurrency techniques using the sync
package. Stay tuned!