~/Reading Piped Text in Golang
Jul 10, 2019
To read text piped into a Go program, you typically use os.Stdin. This allows you to receive data from another command via the | (pipe) operator. Here is a brief example:
Save this as main.go and run:
|
|
This prints hello world to stdout. os.Stdin represents the standard input, so data piped from another process is read by scanner.Scan()
line by line. For more on pipes and piping, read the Linux pipes documentation.
If you need all input as a single string or binary blob, use io.ReadAll:
The process is the same regardless of how data enters your program. Just direct the input via the pipe operator and use os.Stdin as shown above.