Home >Backend Development >Golang >How Can I Check for Available Input on STDIN in Golang?

How Can I Check for Available Input on STDIN in Golang?

DDD
DDDOriginal
2024-12-18 20:06:11630browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn