Search⌘ K
AI Features

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:

  • bufio to read data from files.
  • errors to define error values.
  • fmt to print formatted output.
  • io/ioutil to write data to files.
  • os for operating system-related functions.
  • sort to sort the hosts list content.
Go (1.6.2)
// Package scan provides types and functions to perform TCP port
// scans on a list of hosts
package scan
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"sort"
)

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 ...