Home > Backend Development > Golang > How Can I Check for Data Availability in Standard Input (Stdin) Using Go?

How Can I Check for Data Availability in Standard Input (Stdin) Using Go?

Linda Hamilton
Release: 2024-11-03 13:11:30
Original
1009 people have browsed it

How Can I Check for Data Availability in Standard Input (Stdin) Using Go?

Checking Data Availability in Standard Input (Stdin) Using Go

In Go, the os package provides the os.Stdin variable to access the standard input stream. However, this stream may sometimes block if no data is available for reading. To determine if data is present in the input stream, os.Stdin can be treated like a file and its size can be checked.

Solution:

As os.Stdin behaves like a file, its Stat() method can be used to retrieve file information, including its size. Here's an example:

<code class="go">package main

import (
    "fmt"
    "os"
)

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>
Copy after login

Usage:

This code can be used as an executable file "pipe":

<code class="bash">$ ./pipe
Stdin is empty
$ echo test | ./pipe
5 bytes available in Stdin</code>
Copy after login

In the first line, the pipe executable is run with no input, resulting in an empty standard input and the output "Stdin is empty." In the second line, the text "test" is piped into the input, causing the size of Stdin to increase, and the output changes to "5 bytes available in Stdin."

The above is the detailed content of How Can I Check for Data Availability in Standard Input (Stdin) Using 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