Home > Backend Development > Golang > How Can I Detect if Input is Piped to STDIN in Go?

How Can I Detect if Input is Piped to STDIN in Go?

Patricia Arquette
Release: 2024-12-29 18:27:14
Original
955 people have browsed it

How Can I Detect if Input is Piped to STDIN in Go?

Detecting Input on STDIN in Golang

When developing command-line utilities, it's often necessary to distinguish between input being piped from another program or entered interactively. This article addresses how to check if data is present on STDIN in Go.

Example

Consider the following code:

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")
    }
}
Copy after login

When invoked with piped input (e.g., echo foo | go run test.go), this code correctly identifies the input. However, if called interactively (without piped input), the program indefinitely waits at ioutil.ReadAll(os.Stdin).

Solution

To differentiate between piped and non-piped input, utilize os.ModeCharDevice. This mode identifies whether the input is from a terminal or not. If it's not from a terminal, it's likely piped.

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")
}
Copy after login

The above is the detailed content of How Can I Detect if Input is Piped to STDIN in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template