Computer scienceProgramming languagesGolangPackages and modulesStandard libraryContext package

Context cancellation and timeouts

Let's cancel again with cause

Report a typo

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

Modify the commented parts of the code so that it cancels the context as soon as doSomethingAndFail fails and print cancelMessage

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

Tip: Use Err method of Context type.

Sample Input 1:

the context was canceled because of the error:

Sample Output 1:

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

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

const predefinedTimeout = time.Second * 5

func doSomethingAndFail() error {
time.Sleep(time.Second * 2)
return errors.New("something is not done successfully")
}

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

go func() {
if err := doSomethingAndFail(); err != nil {
// and here
...
}
}()

select {
case <-time.After(predefinedTimeout):
fmt.Println("timed out")
return

Create a free account to access the full topic