Home > Article > Backend Development > How to Check for Data in Stdin without Blocking in Go?
In Go, interacting with standard input (stdin) is often a crucial task when working with commands and pipelines. However, determining if stdin has data without blocking the program's execution can be challenging.
The os.Stdin file object represents stdin, and it possesses capabilities similar to other file objects in Go. This allows us to leverage the Stat function to gather information about stdin, including its size.
To ascertain whether stdin contains data, we can check its size using the following code:
<code class="go">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>
When this code is compiled into an executable, it can be used as a filter to process input piped into stdin. For example, executing the command echo test | ./executable would print "5 bytes available in Stdin" to the console, indicating that stdin contains data. Conversely, running ./executable without any input would display "Stdin is empty."
This approach allows developers to check for data in stdin without blocking and proceed with their program's logic accordingly. It is particularly useful when working with pipelines or handling user input from stdin.
The above is the detailed content of How to Check for Data in Stdin without Blocking in Go?. For more information, please follow other related articles on the PHP Chinese website!