Search⌘ K

Manage the Hosts List Under the Hosts Subcommand

Explore how to implement hosts list management in a Go CLI application using the Cobra framework. Learn to define list, add, and delete subcommands with proper argument validation and error handling. This lesson guides you through loading, updating, and deleting hosts from a file and prepares you to test the CLI commands.

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:

Go (1.6.2)
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
}
Defining the listAction() function

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