Command-Line Flags
Explore how to enhance a basic Go CLI application by adding command-line flags to switch between counting lines or words. Learn to use the Go flag package, update functions for flag input, write tests for new features, and cross-compile the tool for various platforms.
Good command-line tools provide flexibility through options. The current version of the word counter tool only counts words. Let’s add the ability to also count lines by giving the user the option to decide when to switch this behavior through command-line flags. Go provides the flag package, which can be used to create and manage command-line flags.
Adding command-line flags
Let’s open the main.go file and add this package to our imports section:
Next, we’ll update the main() function by adding the definition for the new command-line flag:
This defines a new -l option that we’ll use to indicate whether to count lines. The default value is false, which means that the normal behavior is to count words.
We complete the main() function by updating the call to the function ...