I have a REPL app in Go that should react to keyboard press events (distinct action for each key pressed key) but ReadString
expects for return key to be pressed before reading os.Stdin
:
import (
"bufio"
"os"
)
for {
reader := bufio.NewReader(os.Stdin)
key, _ := reader.ReadString('
')
deferKey(key)
}
How can I react to key press events in Go?
Game engines commonly implement this kind of functionality. They are usually also pretty much platform agnostic (usually at least Windows, Linux, Mac OS X). Try for instance Azul3D's keyboard library.
The logic is off the top of my head something like
watcher := keyboard.NewWatcher()
// Query for the map containing information about all keys
status := watcher.States()
left := status[keyboard.ArrowLeft]
if left == keyboard.Down {
// The arrow to left is being held down
// Do something!
}
Getting a list of what keys are currently being pressed down is a matter of iterating the map through and listing the keys where value was Down.