In Go,context
The package provides a method of passing signals between goroutines to manage the life cycle of requests and control concurrent operations.context
Mainly used in the following scenarios:
1. Control the life cycle of requests
Scene description
- When processing HTTP requests, it is usually necessary to ensure that the request processing can be canceled, timed out or ended in a timely manner. This is especially important when a request involves multiple downstream service calls, if one service responds slowly or fails, all other ongoing operations must be cancelled.
Example of usage
func handler(w , r *) { ctx := () resultChan := make(chan string) go func() { // Simulation time-consuming operation (2 * ) resultChan <- "result" }() select { case <-(): // Request cancel or timeout (w, "request canceled", ) case result := <-resultChan: //Return results normally (w, result) } }
- Explanation: In this example, by
()
To listen to whether the request has been cancelled or timed out, thereby determining whether to terminate the operation.
2. Processing timeouts and deadlines
Scene description
- When handling operations that require network calls or long-running operations, it is important to set a timeout or deadline.
context
You can pass a timeout or deadline to automatically cancel the operation to avoid wasting resources.
Example of usage
func fetchData(ctx ) (string, error) { ctx, cancel := (ctx, 2*) defer cancel() ch := make(chan string, 1) go func() { // Simulation time-consuming operation (3 * ) ch <- "data" }() select { case <-(): return "", () // Return timeout or cancel error case result := <-ch: return result, nil } }
- explain:
Created a timeout
context
, when the operation exceeds the specified time,()
Will be triggered.
3. Pass metadata
Scene description
- In a microservice architecture, it may be necessary to pass some request-related metadata between services, such as authentication information, tracking ID, etc.
context
Provides a way to convey this information.
Example of usage
func main() { ctx := () ctx = (ctx, "requestID", "12345") processRequest(ctx) } func processRequest(ctx ) { reqID := ("requestID") ("Request ID:", reqID) }
- explain:
The requested metadata can be stored in
context
, and passed and accessed throughout the request chain.
4. Work together
Scene description
- In complex concurrent tasks, different goroutines may need to collaborate with each other, or need to cancel other goroutines under specific conditions.
context
It can be used to work together to manage the status of multiple goroutines in a unified manner.
Example of usage
func main() { ctx, cancel := (()) go worker(ctx, "worker1") go worker(ctx, "worker2") (1 * ) cancel() // Cancel all work (1 * ) } func worker(ctx , name string) { for { select { case <-(): (name, "stopped") return default: (name, "working") (500 * ) } } }
- explain:
Created a manual cancellation
context
,passcancel()
Functions can cancel all with thiscontext
Associated operations.
5. Limit the number of concurrency
Scene description
- In some cases, it is necessary to limit the number of goroutines executed concurrently to avoid excessive consumption of system resources.
context
can be with semaphore orUse together to achieve concurrent control.
Example of usage
func main() { ctx, cancel := (()) defer cancel() sem := make(chan struct{}, 3) // Limit the concurrency to 3 var wg for i := 0; i < 10; i++ { (1) go func(i int) { defer () sem <- struct{}{} // Get the signal defer func() { <-sem }() // Release signal worker(ctx, i) }(i) } () } func worker(ctx , id int) { select { case <-(): ("worker %d canceled\n", id) return default: ("worker %d working\n", id) (1 * ) } }
- Explanation: In this example, the semaphore is used to limit the number of goroutines running simultaneously, and
context
Used to cancel all work if needed.
6. Summary
context
In Go language, it is mainly used to manage the life cycle of requests, handle timeouts, pass metadata, work together and limit concurrency. It provides a simple and powerful way to manage complex concurrent operations, especially when multiple goroutines are involved. Through reasonable usecontext
, can write more robust and controllable concurrent programs.
This is the article about the usage scenarios of Context in golang. For more related content on golang Context, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!