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 mainimport ("bufio""flag""fmt""io""os""strings""pragprog.com/rggo/interacting/todo")
We’ll use:
- The
bufiopackage to read data from theSTDINinput stream. - The
iopackage to use theio.Readerinterface. - The function
Join()from thestringspackage 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 interface as input. In Go, it’s a good practice to take
interfaces as function arguments instead of concrete types. This approach
increases the flexibility of ...