I want to create a simple program using Go that can get an output in the terminal output. For example:
echo "john" | goprogram
The output is hi john
When using command cat
cat list_name.txt | goprogram
The output using
hi doe
hi james
hi chris
Is there a way to do this using Go?
CodePudding user response:
Read from os.Stdin. Here's an example implementation of the Hi program.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
fmt.Println("hi", s.Text())
}
if s.Err() != nil {
log.Fatal(s.Err())
}
}
This program creates a scanner to read os.Stdin by line. For each line in stdin, the program prints "hi" and the line.