Capturing Input from STDIN

Powerful Command-Line Applications in Go — by Ricardo Gerardi (26 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Increasing Flexibility with Environment Variables | TOC | Exercises 👉

Good command-line tools interact well with your 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. Let’s add one last feature to the program: the ability to add new tasks via STDIN, allowing your users to pipe new tasks from other command-line tools.

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

interacting/todo.v4/cmd/todo/main.go

​ ​import​ (
» ​"bufio"​
​ ​"flag"​
​ ​"fmt"​

» ​"io"​
​ ​"os"​

» ​"strings"​

​ ​"pragprog.com/rggo/interacting/todo"​
​ )

You’ll use the bufio package to read data from the STDIN input stream, the io package to use the io.Reader interface, and the function Join from the strings package to join command-line arguments to compose a task name.

Next, you’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 your functions by allowing…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.