ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() select { case <-time.After(2 * time.Second): fmt.Println("timeout") case <-ctx.Done(): fmt.Println(ctx.Err()) }
func doSomething(ctx context.Context) error { select { case <-time.After(time.Second): return nil case <-ctx.Done(): return ctx.Err() } }This example is a simple function that does something for one second and then returns. It takes a context as a parameter and checks if the context is canceled before continuing. If the context is canceled, it returns the error returned by `ctx.Err()`.