Home  >  Article  >  Backend Development  >  Is there a way to check if standard input (os.Stdin) in Go has data without blocking?

Is there a way to check if standard input (os.Stdin) in Go has data without blocking?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 08:45:29490browse

Is there a way to check if standard input (os.Stdin) in Go has data without blocking?

How to Determine Data Availability in Stdin with Go

Question

In Go, is there a reliable way to check if the input stream (os.Stdin) contains data?

The conventional approach of reading from the stream blocks when no data is available, making it impractical for certain use cases.

Answer

Similar to other files, os.Stdin can be inspected to determine its size, offering a convenient method for data availability detection.

<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>

By utilizing this technique, you can distinguish between empty and non-empty stdin inputs, allowing for a more flexible handling of data availability.

The above is the detailed content of Is there a way to check if standard input (os.Stdin) in Go has data without blocking?. 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