function similar to getchar

前端 未结 6 661
终归单人心
终归单人心 2020-12-04 19:18

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.

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 19:55

    Thanks goes to Paul Rademacher - this works (at least on Mac):

    package main
    
    import (
        "bytes"
        "fmt"
    
        "github.com/pkg/term"
    )
    
    func getch() []byte {
        t, _ := term.Open("/dev/tty")
        term.RawMode(t)
        bytes := make([]byte, 3)
        numRead, err := t.Read(bytes)
        t.Restore()
        t.Close()
        if err != nil {
            return nil
        }
        return bytes[0:numRead]
    }
    
    func main() {
        for {
            c := getch()
            switch {
            case bytes.Equal(c, []byte{3}):
                return
            case bytes.Equal(c, []byte{27, 91, 68}): // left
                fmt.Println("LEFT pressed")
            default:
                fmt.Println("Unknown pressed", c)
            }
        }
        return
    }
    

提交回复
热议问题