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.
Similar to other files, os.Stdin can be inspected to determine its size, offering a convenient method for data availability detection.
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")
}
}
By utilizing this technique, you can distinguish between empty and non-empty stdin inputs, allowing for a more flexible handling of data availability.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3