在golang终端应用程序中以编程方式结束输入

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('
')
    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?

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('
')
    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")
    }
}