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.
Use the _getch() function to give you a character without waiting for the Enter key.
To read input from the console, we need to import a few packages. The first is the bufio package, fmt package, and the os package. The bufio package allows you to read characters from the STDIN at once. The fmt package is used to handle I/O operations, and the os provides low-level system functionalities.
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)+")") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With