readline/example/main.go

75 lines
1.2 KiB
Go
Raw Normal View History

2015-09-20 18:14:29 +03:00
package main
import (
2015-09-25 17:56:00 +03:00
"fmt"
2015-09-20 18:14:29 +03:00
"io"
"log"
"strconv"
2015-09-25 17:56:00 +03:00
"strings"
2015-09-20 18:14:29 +03:00
"time"
"github.com/chzyer/readline"
)
2015-09-21 17:27:40 +03:00
func usage(w io.Writer) {
io.WriteString(w, `
sayhello: start to display oneline log per second
bye: quit
`[1:])
}
2015-09-25 17:56:00 +03:00
type Completer struct {
}
func (c *Completer) Do(line []rune, pos int) (newLine [][]rune, off int) {
list := [][]rune{
[]rune("sayhello"), []rune("help"), []rune("bye"),
}
for i := 0; i <= 100; i++ {
list = append(list, []rune(fmt.Sprintf("com%d", i)))
}
line = line[:pos]
for _, r := range list {
if strings.HasPrefix(string(r), string(line)) {
newLine = append(newLine, r[len(line):])
}
}
return newLine, len(line)
}
2015-09-20 18:14:29 +03:00
func main() {
2015-09-22 13:16:24 +03:00
l, err := readline.NewEx(&readline.Config{
2015-09-25 17:56:00 +03:00
Prompt: "\033[31m»\033[0m ",
HistoryFile: "/tmp/readline.tmp",
AutoComplete: new(Completer),
2015-09-22 13:16:24 +03:00
})
2015-09-20 18:14:29 +03:00
if err != nil {
panic(err)
}
2015-09-21 08:30:10 +03:00
defer l.Close()
2015-09-20 18:14:29 +03:00
log.SetOutput(l.Stderr())
for {
line, err := l.Readline()
if err != nil {
break
}
switch line {
case "help":
2015-09-21 17:27:40 +03:00
usage(l.Stderr())
2015-09-20 18:14:29 +03:00
case "sayhello":
go func() {
for _ = range time.Tick(time.Second) {
log.Println("hello")
}
}()
case "bye":
goto exit
2015-09-21 17:27:40 +03:00
case "":
2015-09-20 18:14:29 +03:00
default:
log.Println("you said:", strconv.Quote(line))
}
}
exit:
}