Starting the Scan Package

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding the First Subcommand to Your Application | TOC | Creating the Subcommands to Mana ge Hosts 👉

You have the skeleton of your application ready, so let’s add the port scanning functionality, starting with the hosts list management. For this tool, you’ll create a separate package scan to develop the business logic, similar to the approach you used in Chapter 2, Interacting with Your Users.

In your application’s root directory, create a new directory named scan and switch to it:

​ ​$ ​​cd​​ ​​$HOME/pragprog.com/rggo/cobra/pScan​
​ ​$ ​​mkdir​​ ​​scan​
​ ​$ ​​cd​​ ​​scan​

Now, create and edit the file hostsList.go. Start by defining the package name scan and the import list. For this package you’ll use the f0llowing 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, and sort to sort the hosts list content:

cobra/pScan.v3/scan/hostsList.go

​ ​// 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"​
​ )

Define two error variables using the function errors.New from the errors package…

--

--

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.