I have a piece of code that needs to be executed every time there is new input in Stdin but the program should not terminate if there is nothing in Stdin instead it should wait for new data in Stdin and then run the computation code for that data.
How can this be achieved in Golang? Below is the piece of the code:
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
fmt.Println("data is being piped to stdin")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text:= scanner.Text()
fmt.Println(text)
// do some computation ....
} else {
fmt.Println("No data in stdin")
// wait until there is new data in Stdin
}
Can someone help me figure a way out to achieve this.
You could wrap your Scan
call in a loop:
for text := ""; text != ""; {
for scanner.Scan() {
text = scanner.Text()
// ...
}
}
This would have the side effect of looping even if the user puts an empty input.