Computer scienceProgramming languagesGolangPackages and modulesStandard libraryContext package

Context cancellation and timeouts

Let's cancel again with timeout

Report a typo

We have an unfinished program! It reads a value from stdin to cancelMessage variable and does a doSomethingAndFail task.

Modify the commented parts of the code so that:

  • the context is canceled by timeout,
  • as soon as the context is canceled the message is printed to the console.

The message should look like this: <cancelMessage variable value> <cancellation error from the context>

Tip: Use context.WithTimeout

Sample Input 1:

the context was canceled because of the error:

Sample Output 1:

the context was canceled because of the error: context deadline exceeded
Write a program in Go
package main

import (
"context"
"fmt"
"time"
"bufio"
"os"
)

// tip: cancelation timeout should be less than the `predefinedTimeout` value!
const predefinedTimeout = time.Second * 5

func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
cancelMessage := scanner.Text()
// write your code here
processingCtx, cancelProcessing := ...

select {
case <-time.After(predefinedTimeout):
fmt.Println("timed out")
cancelProcessing()
return
case <-processingCtx.Done():
// write your code here
return
}
}

Create a free account to access the full topic