Manage the Hosts List Under the Hosts Subcommand
Learn how to write the code to manage the hosts list under the hosts subcommand.
We'll cover the following...
Defining the listAction()
function
Now we define the listAction()
function. It accepts an io.Writer
interface representing where to print output to, the string
hostsFile
that contains the name of the file
to load the hosts list from, and a slice
of string args
that has any other arguments passed by the user. It returns a potential error
. Even though this function doesn’t use the args
parameter, we’ll leave it there so it’s similar to other actions we’ll add later:
func listAction(out io.Writer, hostsFile string, args []string) error {hl := &scan.HostsList{}if err := hl.Load(hostsFile); err != nil {return err}for _, h := range hl.Hosts {if _, err := fmt.Fprintln(out, h); err != nil {return err}}return nil}
This function creates an instance of the HostsList
type provided by the package
scan
we created before. Then, it loads the content of the hostsFile
into the hosts
list instance and iterates over each entry, printing each item into the io.Writer
...