Читать книгу Practical Go - Amit Saha - Страница 63

Listing 2.7: Implementing time-out for user input

Оглавление

// chap2/user-input-timeout/main.go package main import ( "bufio" "context" "errors" "fmt" "io" "os" "time" ) var totalDuration time.Duration = 5 func getName(r io.Reader, w io.Writer) (string, error) { scanner := bufio.NewScanner(r) msg := "Your name please? Press the Enter key when done" fmt.Fprintln(w, msg) scanner.Scan() if err := scanner.Err(); err != nil { return "", err } name := scanner.Text() if len(name) == 0 { return "", errors.New("You entered an empty name") } return name, nil } // TODO Insert getNameContext() definition as above // TODO Insert main() definition as above

Create a new directory, chap2/user-input-timeout, and initialize a module inside it:

$ mkdir -p chap2/user-input-timeout $ cd chap2/user-input-timeout $ go mod init github.com/username/user-input-timeout

Next, save Listing 2.7 as main.go. Build it as follows:

$ go build -o application

Run the program. If you do not input any name within 5 seconds, you will see the following:

$ ./application Your name please? Press the Enter key when done Default Name

However, if you input a name and press Enter within 5 seconds, you will see the name that was entered:

$ ./application Your name please? Press the Enter key when done

John C

John C

You learned to use the WithTimeout() function to create a context that allows you to enforce a limit which is relative to the current time. The WithDeadline() function, on the other hand, is useful when you want to enforce a real-world deadline. For example, if you wanted to ensure that a function must be executed before June 28, 10:00 AM, you could use a context created via WithDeadline() .

Next, you will learn to test such timeout behavior in your applications as part of Exercise 2.3.

EXERCISE 2.3: UNIT TESTING THE TIME-OUT EXCEEDED BEHAVIOR Write a test to verify the time-out exceeded behavior. One straightforward way to do so is not to provide any input at all in the test so that the deadline exceeds. Of course, you should also test the “happy path,” that is, where you provide an input and the deadline doesn't exceed. It is recommended to use a shorter time-out—in the order of a few 100 milliseconds to avoid time-consuming tests.

Practical Go

Подняться наверх