Here, we will are going to learn about context package in Go with deep understanding and example in details.
The context package in Go provides powerful tools to handle timeouts, cancellations, and sharing request-scoped values across multiple API calls.
The context package in Go is designed to facilitate communication between concurrent goroutines, primarily focusing on sharing values and managing deadlines or cancellations. It provides a simple yet powerful way to control and manage the lifecycle of various resources and operations within your application.
Benefits of Using it:
- Deadline Management: The context package allows developers to set deadlines for operations to complete. This ensures that long-running tasks do not monopolize resources indefinitely.
- Cancellation Propagation: Context can efficiently propagate cancellation signals, enabling developers to cancel a group of tasks with a single command.
- Request-scoped Value Sharing: Context allows developers to share values across multiple API calls, simplifying the handling of metadata and other shared data.
Example:
Let’s create a simple example that demonstrates the use of the context package to manage deadlines and cancellations.
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
resultChan := make(chan string)
go func() {
operation(ctx, resultChan)
}()
select {
case res := <-resultChan:
fmt.Println("Operation completed:", res)
case <-ctx.Done():
fmt.Println("Operation timed out:", ctx.Err())
}
}
func operation(ctx context.Context, resultChan chan string) {
select {
case <-time.After(200 * time.Millisecond):
resultChan <- "Success"
case <-ctx.Done():
return
}
}
In this example, we create a context with a timeout of 100 milliseconds using context.WithTimeout
. We then launch a goroutine that simulates a long-running operation. If the operation completes within the timeout, we print the result. If not, we print an error message indicating that the operation has timed out.
Context functions
To learn more about golang, Please refer given below link.
https://techieindoor.com/go-net-package-in-go-golang/
References: