0

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?

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • Write a program that reads from stdin. You can use fmt.Scan functions – Burak Serdar Sep 13 '21 at 03:03
  • Does this answer your question? [How can I read from standard input in the console?](https://stackoverflow.com/questions/20895552/how-can-i-read-from-standard-input-in-the-console) – MenyT Sep 13 '21 at 18:42

1 Answers1

1

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.