My purpose is to print string sequentially and when the user enter some character, we pause the process and read stdin content. I know it's possible to catch os.Interrupt signal but I don't how to catch event in stdin. I don't want to scan and wait user to enter text. The process is stopped when there is a keypress event.
My question : How detect event on stdin ?
Thanks !
Here is current solution with your advice. Go routines not constitue an optimal solution because you can't manage them as threads. I currently continue working on this and keep you udpated. Edit :
func main() {
quit := make(chan bool)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
fmt.Println("-----------------")
fmt.Println("Go routine running :", runtime.NumGoroutine())
go func() {
select {
case <-quit:
return
default:
fmt.Println("Text received and changed")
fmt.Println("-----------------")
for {
timer := time.NewTimer(time.Second * 1)
<-timer.C
fmt.Println(scanner.Text())
}
}
fmt.Println("Routine closed")
}()
}
if scanner.Err() != nil {
quit <- false
}
}
Otherwise if I follow your solution @varius :
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
for {
timer := time.NewTimer(time.Second * 1)
<-timer.C
fmt.Println(scanner.Text())
}
}
if scanner.Err() != nil {
/*handle error*/
}
}
But I can't change the scan content while program running.