ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() // do some work select { case <-ctx.Done(): fmt.Println("Timeout exceeded") return default: fmt.Println("Work completed within timeout") return }
ctx := context.WithValue(context.Background(), "key", "value") // pass context to other functions value := ctx.Value("key").(string) fmt.Println(value)
ctx, cancel := context.WithCancel(context.Background()) defer cancel() // do some work if someCondition { cancel() // cancel the context }This creates a new context with a cancellation function and cancels it when a certain condition is met. Overall, the "context" package is essential for managing request-scoped values, deadlines, and cancellations in Go.