Maxim Yefremov
Maxim Yefremov

Reputation: 14165

end input programmatically in a golang terminal application

I am trying to end terminal input programmatically in 3 seconds and output the result.

My code is the following:

package main

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

var (
    result string
    err    error
)

func main() {
    fmt.Println("Please input something, you have 3000 milliseconds")
    go func() {
        time.Sleep(time.Millisecond * 3000)
        fmt.Println("It's time to break input and read what you have already typed")
        fmt.Println("result")
        fmt.Println(result)
    }()
    in := bufio.NewReader(os.Stdin)
    result, err = in.ReadString('\n')
    if err != nil {
        fmt.Println(err)
    }
}

The output:

Please input something, you have 3000 milliseconds
hello It's time to break input and read what you have already typed
result

I just printed hello and 3 seconds passed and the program should end the input and read my hello and give output:

result
hello

But I don't know how to provide this. Is it possible to end terminal input without user's intention and read the inputted value?

Upvotes: 2

Views: 775

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109337

You can't timeout the read on stdin directly, so you need to create a timeout around receiving the result from the reading goroutine:

func getInput(input chan string) {
    in := bufio.NewReader(os.Stdin)
    result, err := in.ReadString('\n')
    if err != nil {
        log.Fatal(err)
    }

    input <- result
}

func main() {
    input := make(chan string, 1)
    go getInput(input)

    select {
    case i := <-input:
        fmt.Println(i)
    case <-time.After(3000 * time.Millisecond):
        fmt.Println("timed out")
    }
}

Upvotes: 2

Related Questions