Is there a Go function similar to C\'s getchar able to handle tab press in console? I want to make some sort of completion in my console app.
Other answers here suggest such things as:
Using cgo
os.Exec of stty
using code that uses /dev/tty
using a GNU readline package
However, for the simple case this is easy just using a package from the Go Project's Sub-repositories.
Basically, use terminal.MakeRaw and terminal.Restore to set standard input to raw mode (checking for errors, e.g. if stdin is not a terminal); then you can either read bytes directly from os.Stdin, or more likely, via a bufio.Reader (for better efficiency).
For example, something like this:
package main
import (
"bufio"
"fmt"
"log"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
// fd 0 is stdin
state, err := terminal.MakeRaw(0)
if err != nil {
log.Fatalln("setting stdin to raw:", err)
}
defer func() {
if err := terminal.Restore(0, state); err != nil {
log.Println("warning, failed to restore terminal:", err)
}
}()
in := bufio.NewReader(os.Stdin)
for {
r, _, err := in.ReadRune()
if err != nil {
log.Println("stdin:", err)
break
}
fmt.Printf("read rune %q\r\n", r)
if r == 'q' {
break
}
}
}