Exercise: Adding and Validating Flags

Test your coding skills on the Cobra CLI framework.

Challenge

In this exercise, your challenge is to add a new flag and some validation to the pScan tool.

Problem Statement

Add a new flag to pScan scan subcommand allowing the user to specify a filter to show only open or closed ports.

Coding Challenge

Add a new flag to the subcommand scan of the pScan tool you developed in this Chapter. This new flag allows the user to specify a filter to define how to display the results. The flag should be defined as String, and it should accept the parameters “all,” “open,” and “closed.” Add a validation function to ensure users specify only one of those values and present the command usage in any other case.

Update the printResults function to accept the filter parameter with the value set in the newly added flag. Change how it display the results based on the flag, display “all” ports by default, or only “open” or “closed” ports depending on the user’s choice.

Start from the pScan implementation at the end of this Chapter. You can use the PreRunE action function from the cobra.Command type to implement a validation function that executes before the actual RunE action. You can also implement the validation function in a different way if you prefer.

If you feel stuck, refer to Cobra’s CLI framework documentation. If you still need help, check the solution review in the next lesson. Good luck!

Note: For an extra challenge, add tests for the printResults function to test the filter.

Get hands-on with 1200+ tech skills courses.