Checking Data Availability in Standard Input (Stdin) Using Go
In Go, the os package provides the os.Stdin variable to access the standard input stream. However, this stream may sometimes block if no data is available for reading. To determine if data is present in the input stream, os.Stdin can be treated like a file and its size can be checked.
Solution:
As os.Stdin behaves like a file, its Stat() method can be used to retrieve file information, including its size. Here's an example:
<code class="go">package main import ( "fmt" "os" ) func main() { file := os.Stdin fi, err := file.Stat() if err != nil { fmt.Println("file.Stat()", err) } size := fi.Size() if size > 0 { fmt.Printf("%v bytes available in Stdin\n", size) } else { fmt.Println("Stdin is empty") } }</code>
Usage:
This code can be used as an executable file "pipe":
<code class="bash">$ ./pipe Stdin is empty $ echo test | ./pipe 5 bytes available in Stdin</code>
In the first line, the pipe executable is run with no input, resulting in an empty standard input and the output "Stdin is empty." In the second line, the text "test" is piped into the input, causing the size of Stdin to increase, and the output changes to "5 bytes available in Stdin."
The above is the detailed content of How Can I Check for Data Availability in Standard Input (Stdin) Using Go?. For more information, please follow other related articles on the PHP Chinese website!