Search code examples
gostdin

Read a character from standard input in Go (without pressing Enter)


I want my app to show:

press any key to exit ...

And to exit when I press any key.

How can I achieve this?

Note: I have googled but all of what I've found needed to press Enter at the end. I want something like Console.ReadKey() in C#.

I am running MS Windows.


Solution

  • The package "golang.org/x/term" allows you to switch the stdin into raw mode to read each byte at a time.

    package main
    
    import (
        "fmt"
        "os"
    
        "golang.org/x/term"
    )
    
    func main() {
        // switch stdin into 'raw' mode
        oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
        if err != nil {
            fmt.Println(err)
            return
        }
        defer term.Restore(int(os.Stdin.Fd()), oldState)
    
        b := make([]byte, 1)
        _, err = os.Stdin.Read(b)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("the char %q was hit", string(b[0]))
    }