Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

stdin

go

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.

like image 975
Kaveh Shahbazian Avatar asked Mar 01 '13 13:03

Kaveh Shahbazian


People also ask

How do you take input without entering?

Use the _getch() function to give you a character without waiting for the Enter key.

How do you read standard input in go?

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.


1 Answers

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)+")")     } } 
like image 95
blinry Avatar answered Oct 12 '22 22:10

blinry