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

Kaveh Shahbazian picture Kaveh Shahbazian · Mar 1, 2013 · Viewed 15.4k times · Source

I want to my app shows:

press any key to exit ...

And when I pressed any key, it exits.

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.

Answer

blinry picture blinry · Jun 24, 2013

This is a minimal working example for those running a UNIX system:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    // disable input buffering
    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    // do not display entered characters on the screen
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()

    var b []byte = make([]byte, 1)
    for {
        os.Stdin.Read(b)
        fmt.Println("I got the byte", b, "("+string(b)+")")
    }
}