package main

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

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

	// do some work asynchronously
	go func() {
		fmt.Println("doing some work...")
		time.Sleep(2 * time.Second)
		fmt.Println("finished with work")
		// call the cancel function when done working
		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...
context finished
2021/02/08 13:30:38 context deadline exceeded
exit status 1
// section: output

*/
