Menu Close

Context package in Go

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:

  1. 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.
  2. Cancellation Propagation: Context can efficiently propagate cancellation signals, enabling developers to cancel a group of tasks with a single command.
  3. 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://www.techieindoor.com/go-net-package-in-go-golang/

References:

https://golang.org/doc/

Posted in context, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *