package main import ( "context" "net/http" "time" ) func main() { // Create a context with a 10-second deadline ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second)) defer cancel() // Make a network request with the context object req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) if err != nil { // Handle error } client := &http.Client{} resp, err := client.Do(req) if err != nil { // Handle error } // Handle response }
package main import ( "context" "fmt" "time" ) func main() { // Create a context with a 5-second deadline ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) defer cancel() // Start a goroutine with the context object go func(ctx context.Context) { for { select { case <-ctx.Done(): // Context has been canceled, return return default: // Do some work fmt.Println("working...") time.Sleep(time.Second) } } }(ctx) // Wait for 10 seconds before exiting time.Sleep(10 * time.Second) }In this example, we create a new context object with a deadline of 5 seconds using the WithDeadline function. We then start a new goroutine that performs some work in a loop, checking if the context has been canceled using the Done function of the context object. If the 5-second deadline is exceeded, the goroutine will be canceled automatically, and the program will exit after 10 seconds. The Go Context package is used for managing request-scoped values, cancelation signals across multiple goroutines, and timeouts across an API boundary. This provides a clear way to manage context across multiple systems and microservices.