Search code examples
goterminalstdin

Read SPACE without ENTER as input from terminal


I had a CLI program which will ask user to type ENTER to continue and OTHER keys to abort.

for {
    show() // list one page

    fmt.Printf("Press ENTER to show next page, press any other key then Enter to quit")
    var input string
    fmt.Scanln(&input)
    if strings.Trim(input, " ") == "" {
        continue
    } else {
        break
    }
}

I want to improve user experience: instead of "ENTER or press something then ENTER", how can I make it "Press SPACE to show next page, press q to quit", just like Linux command "more" and others.

To make it clear:

  • The existing control to continue is "ENTER", I want to use "SPACE" (just SPACE, not SPACE+ENTER);
  • The existing control to quit is "any key + ENTER", I want to use "q" (just q, not q+ENTER)

Solution

  • There is a built in shell command read -n1 -r -p "Press SPACE to show next page, press q to quit" key. Possibly you could exec that.

    For a more full featured golang solution, see github.com/nsf/termbox-go. Good example: https://www.socketloop.com/tutorials/golang-get-ascii-code-from-a-key-press-cross-platform-example