从终端输入时不输入ENTER读取SPACE

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)

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

A simple solution with github.com/nsf/termbox-go

package main

import (
    "fmt"
    tb "github.com/nsf/termbox-go"
)

func main() {
    err := tb.Init()
    if err != nil {
        panic(err)
    }
    defer tb.Close()
    for {
        fmt.Println("Press any key")
        event := tb.PollEvent()
        switch {
        case event.Ch == 'a':
            fmt.Println("a")
        case event.Key == tb.KeyEsc:
            fmt.Println("Bye!")
            return
        case event.Key == tb.KeySpace:
            fmt.Println("ANY KEY! You pressed SPACE!")
        case event.Key == tb.KeyEnter:
            fmt.Println("ANY KEY! You pressed ENTER!")
        default:
            fmt.Println("Any key.")
        }
    }
}