Golang: Read from STDIN and block until there is something being sent to STDIN

Viewed 56

trying to figure out how to read from STDIN in a loop in Go / Golang and block while there is nothing there. I am trying to have a parent program execute this one as a child with a pipe to write to the child STDIN and read from child STDOUT. I get through the first iteration fine, but then EOF is returned every time on subsequent reads without blocking and loops infinitely. I have tried using bufio.Reader, bufio.Scanner, and fmt.Scan and I keep getting the EOF error and looping infinitely. I commented out the Scanner and Reader implementations to show you what I tried. Here is what I have so far:

    // loop until we are told to shutdown
    //scanner := bufio.NewScanner(os.Stdin)
    //reader := bufio.NewReader(os.Stdin)
    for {

        // reads lines from STDIN
        // WANT TO BLOCK HERE UNTIL SOMETHING SENT TO STDIN
        //var line []byte
        //if scanner.Scan() {
        //line = scanner.Bytes()
        //}
        //line, err := reader.ReadString('\n')
        line := ""
        _, err := fmt.Scan(&line)
        if err != nil {
            log.Printf("Issue reading\n%s", err)

        }
        if line == "stop" {
            break
        }
}

No sure what to do here besides maybe use a pipe? Any help is appreciated.

1 Answers

Shouldn't be any more difficult than:

scanner := bufio.NewScanner(os.Stdin)

for scanner.Scan() {
  line := scanner.Text()

  if line == "stop" {
    break
  }
  
  fmt.Printf("You entered: %s\n", line)
  
}

if err := scanner.Err(); err != nil {
  panic(err)
}
Related