package main

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

// section: main
func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// do some work asynchronously
	go func() {
		fmt.Println("doing some work...")
		// call the cancel function when done working
		time.Sleep(2 * time.Second)
		fmt.Println("finished with work")
		cancel()
	}()

	// code waits for context to finish via `cancel` function
	<-ctx.Done()
	fmt.Println("context finished")

	// Check the error
	err := ctx.Err()
	if err != context.Canceled {
		log.Fatal(err)
	}
}

// section: main

/*
// section: output
doing some work...
finished with work
context finished
// section: output

*/
