Sobes.tech
Middle

What opportunities does creating a child data context in Go provide?

sobes.tech AI

Answer from AI

Creating a child context (using context.WithCancel, context.WithDeadline, context.WithTimeout, context.WithValue) provides the following capabilities:

  • Cancellation: Allows canceling operations running in the child context without affecting the parent. This is achieved by calling the cancel function returned when creating the context.
  • Timeout / Deadline: Limits the execution time of operations. If the time expires before the operation completes, the context is automatically canceled.
  • Passing values: Enables passing request-specific or operation-specific values down the call chain (e.g., request ID, authentication data) without changing function signatures.
  • Hierarchy: Creates a hierarchical structure of contexts. Canceling the parent context automatically cancels all its child contexts.
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	// Parent context that cancels after 3 seconds
	parentCtx, cancelParent := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancelParent() // Ensure the parent context will be canceled

	// Create a child context with cancellation
	childCtx, cancelChild := context.WithCancel(parentCtx)
	defer cancelChild() // Ensure the child context will be canceled

	// Function that waits for context cancellation
	go func(ctx context.Context) {
		select {
		case <-ctx.Done():
			// This block executes when the context is canceled
			fmt.Println("Child goroutine canceled:", ctx.Err())
		}
	}(childCtx) // Pass the child context to the goroutine

	// Artificial delay for demonstration of cancellation
	time.Sleep(5 * time.Second)

	fmt.Println("Program finished")
}

In this example, the parent context with a timeout of 3 seconds will automatically cancel the child context, leading to the termination of the goroutine. The child context could also be canceled manually by calling cancelChild() before the parent context's timeout expires.