Home >Backend Development >Golang >How Can I Detect if STDIN Contains Data in Go?
This code snippet addresses the issue of checking for input on the standard input (STDIN) using the Go language. In particular, the user encounters a situation where their command-line utility needs to behave differently based on the presence of a string being piped into STDIN.
The provided example code uses the ioutil.ReadAll(os.Stdin) function to read all the bytes from STDIN. If the length of the byte array is greater than zero, the code prints an appropriate message indicating that something is available on STDIN. However, when there is nothing on STDIN, the code can get stuck waiting for an end-of-file (EOF) marker.
To resolve this issue, the code leverages the os.ModeCharDevice flag to determine if STDIN is coming from a terminal or a pipe. If the os.ModeCharDevice flag is not set, it indicates that data is being piped into STDIN, and the code prints a message accordingly. Otherwise, it assumes that STDIN is coming from a terminal.
Here's the modified code snippet incorporating the os.ModeCharDevice check:
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") }
This code effectively allows the command-line utility to distinguish between piped input and direct terminal input, enabling it to behave accordingly.
The above is the detailed content of How Can I Detect if STDIN Contains Data in Go?. For more information, please follow other related articles on the PHP Chinese website!