How to Read from Initial stdin in Go
In Go, reading from the initial stdin of a program can be achieved using the os.Stdin interface. However, if there is no input in os.Stdin, the program will wait for input.
Solution:
The recommended approach is to use os.Stdin as it provides a simple and reliable method for reading from the original stdin. To use os.Stdin, simply call the io.ReadAll() function to read all the bytes from the input.
Here's an example:
package main import "os" import "log" import "io" func main() { bytes, err := io.ReadAll(os.Stdin) log.Println(err, string(bytes)) }
When executed with echo test stdin | go run stdin.go, this code will print test stdin.
For line-based reading, the bufio.Scanner can be used:
import "os" import "log" import "bufio" func main() { s := bufio.NewScanner(os.Stdin) for s.Scan() { log.Println("line", s.Text()) } }
The above is the detailed content of How to Read from Standard Input (stdin) in Go?. For more information, please follow other related articles on the PHP Chinese website!