Starting the Scan Package
Explore how to create a Go scan package that handles a list of hosts for port scanning. Learn to implement methods for adding, removing, loading, and saving hosts, and apply table-driven tests to ensure robustness and error handling in your command-line tool.
We have the skeleton of our application ready, so let’s add the port scanning
functionality, starting with the hosts list management. For this tool, we’ll create a separate package scan to develop the business logic.
Creating the hostsList.go file
Now, we create and edit the file hostsList.go. We start by defining the package name scan and the import list.
For this package, we’ll use the following packages:
bufioto read data from files.errorsto define error values.fmtto print formatted output.io/ioutilto write data to files.osfor operating system-related functions.sortto sort the hosts list content.
We define two error variables using the function errors.New() from the errors package.
The first error variable, ErrExists, indicates that a host is already in the list, and the second error variable, ErrNotExists, indicates that a host isn’t in the list. We’ll use these errors during tests and to ...