Handling Multiple Command-Line Options

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing the Initial CLI Implementati on | TOC | Display Command-Line Tool Usage 👉

As you’ve seen while implementing the initial version of your command-line interface, using the os.Args variable isn’t a flexible way of handling command-line arguments. Let’s improve the tool by using the flag package to parse and handle multiple command-line options.

The flag package enables you to define command-line flags of specific types such as int or string so you don’t need to convert them manually.

This version of the tool will accept three command-line arguments:

  1. -list: A Boolean flag. When used, the tool will list all to-do items.
  2. -task: A string flag. When used, the tool will include the string argument as a new to do item in the list.
  3. -complete: An integer flag. When used, the tool will mark the item number as completed.

Example Code

INFORMATION

The complete example code for this section is under a subdirectory named todo.v1 to make it easy to find. In your case, it may be easier to simply update the existing code.

To use the flag package, include it in the import section of your program:

--

--

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.