gitee.com/KyleChenSource/lib-robot@v1.0.2/robottest/common/interaction/stdinput.go (about) 1 package interaction 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "sync" 8 ) 9 10 var ( 11 input *StdInput 12 ) 13 14 const ( 15 ctxkey_input_flag = "input_flag" 16 ) 17 18 type StdInput struct { 19 reader_ *bufio.Reader 20 cmds_ chan string // 输入指令, 用于允许输入开始,结束输入,清理之类的指令 21 lines_ chan string // 终端输入 22 23 input_signal_ chan any 24 ctx_ sync.Map 25 } 26 27 func Input() *StdInput { 28 if input == nil { 29 // info, _ := os.Stdin.Stat() 30 // fmt.Printf("std:%T %v", info, info) 31 input = &StdInput{ 32 reader_: bufio.NewReader(os.Stdin), 33 cmds_: make(chan string, 1024), 34 lines_: make(chan string), 35 input_signal_: make(chan any), 36 } 37 38 go co_input(input) 39 } 40 41 return input 42 } 43 44 func (this *StdInput) Want() { 45 this.clear() 46 47 this.input_signal_ <- struct{}{} 48 } 49 50 func (this *StdInput) Line() <-chan string { 51 return this.lines_ 52 } 53 54 func (this *StdInput) clear() { 55 for { 56 select { 57 case <-this.lines_: 58 // 丢弃之前的所有输入 59 60 default: 61 return 62 } 63 } 64 } 65 66 func co_input(in *StdInput) { 67 line := make([]byte, 0) 68 for { 69 <-in.input_signal_ 70 71 fmt.Print("$请输入指令:") 72 line = line[:0] 73 bLine := true 74 for bLine { 75 r, _, e := in.reader_.ReadRune() 76 if e != nil { 77 fmt.Printf("输入终端错误:%s,进行恢复尝试", e.Error()) 78 in.reader_ = bufio.NewReader(os.Stdin) 79 in.lines_ <- "" 80 break 81 } 82 83 switch r { 84 case '\b': 85 fmt.Print('\b') 86 if len(line) > 0 { 87 line = line[0 : len(line)-1] 88 } 89 case '\n': 90 bLine = false 91 break 92 default: 93 line = append(line, []byte(string(r))...) 94 } 95 } 96 97 in.lines_ <- string(line) 98 } 99 }