-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnbreadline.go
67 lines (57 loc) · 1007 Bytes
/
nbreadline.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package nbreadline
import (
"bufio"
"errors"
"fmt"
"os"
)
type Reader struct {
cmd string
err chan error
data chan string
ctrl chan bool
prompt string
sentinal byte
}
func (r *Reader) New() {
r.err = make(chan error)
r.ctrl = make(chan bool)
r.data = make(chan string)
r.sentinal = '\n'
r.prompt = "> "
go r.readLine()
}
func (r *Reader) Close() {
// This will cause a deadlock - there is no way to close the routine
// given that the readline blocks.
//r.ctrl <- true
}
func (r *Reader) ReadLine() (string, error) {
select {
case cmd := <-r.data:
return cmd, nil
case err := <-r.err:
return "", err
default:
return "", errors.New("Unknown state")
}
}
func (r *Reader) readLine() {
reader := bufio.NewReader(os.Stdin)
for {
select {
case ctrl := <-r.ctrl:
if ctrl {
return
}
default:
fmt.Printf(r.prompt)
s, err := reader.ReadString(r.sentinal)
if err != nil {
r.err <- err
} else {
r.data <- s
}
}
}
}