AI Features

Capturing Input from STDIN

Learn how to get input from STDIN.

Good command-line tools interact well with our users, but they also work well with other tools. A common way command-line programs interact with one another is by accepting input from the standard input (STDIN) stream.

Adding a feature

Let’s add one last feature to the program: the ability to add new tasks via STDIN, allowing our users to pipe new tasks from other command-line tools.

To start this update, we add three new libraries to our main.go import list: bufio, io, and strings.

package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"strings"
"pragprog.com/rggo/interacting/todo"
)

We’ll use:

  • The bufio package to read data from the STDIN input stream.
  • The io package to use the io.Reader interface.
  • The function Join() from the strings package to join command-line arguments to compose a task name.

Next, we’ll create a new helper function called getTask() that will determine where to get the input task from. This function leverages Go interfaces again by accepting the io.Reader ...