-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetch.go
43 lines (36 loc) · 832 Bytes
/
getch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package getch
import (
"errors"
"io"
"os"
)
var (
hStdin = os.Stdin.Fd()
isTerm = isTerminal()
errNotInTerminal = errors.New("error not in terminal")
)
// Getch get the pressed key directly without buffering, no need to enter enter to get.
func Getch() (rune, []byte, error) {
return GetchBy(hStdin)
}
// GetchBy get the pressed key directly without buffering, no need to enter enter to get.
func GetchBy(hStdin uintptr) (rune, []byte, error) {
if !isTerm {
return 0, nil, errNotInTerminal
}
state, err := makeRaw(hStdin)
if err != nil {
return 0, nil, err
}
defer restored(hStdin, state)
var buf [6]byte
n, err := read(hStdin, buf[:])
if err != nil {
return 0, nil, err
}
if n == 0 {
return 0, nil, io.ErrUnexpectedEOF
}
key, raw := Bytes2Key(buf[:n])
return key, raw, nil
}