Home >Backend Development >Golang >How Can I Check for Available Input on STDIN in Golang?
Checking for Available Input on STDIN in Golang
In certain command-line scenarios, understanding whether input exists on stdin is crucial for tailored behavior. Consider the following example:
package main import ( "fmt" "io/ioutil" "os" ) func main() { bytes, _ := ioutil.ReadAll(os.Stdin) if len(bytes) > 0 { fmt.Println("Something on STDIN: " + string(bytes)) } else { fmt.Println("Nothing on STDIN") } }
While this code functions for piped input, it halts at ioutil.ReadAll(os.Stdin) when no input is present. This article addresses this issue, providing a solution to determine the availability of stdin data.
Solution: Checking the File Mode
The solution lies in examining the file mode of the stdin stream. When stdin is a regular file (e.g., a terminal), its mode includes os.ModeCharDevice, indicating character device status. Conversely, if input is piped, the mode lacks this flag. The following code demonstrates this approach:
package main import ( "fmt" "os" ) func main() { stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { fmt.Println("data is being piped to stdin") } else { fmt.Println("stdin is from a terminal") } }
With this modification, your program can distinguish between piped and terminal-based stdin inputs, allowing for appropriate behavior adjustments.
The above is the detailed content of How Can I Check for Available Input on STDIN in Golang?. For more information, please follow other related articles on the PHP Chinese website!