...

/

Implementing Application I/O

Implementing Application I/O

Learn application I/O by understanding flags and handling basic flag errors.

CLI applications require a way to understand how we want them to execute. This might include what files to read, what servers to contact, and what credentials to use. There are a couple of ways to start an application with the parameters it requires:

  • Using the flag package to define command-line flags.

  • Using os.Args to read arguments that are not defined.

The flag package will help us when we have a command-line argument that has a strict definition. This might be an argument that defines the endpoint for a needed service. The program might want to have a default value for production but allow an override when doing testing. This is perfect for a flag.

An example might be a program that queries our Quote of the Day (QOTD) server that we created earlier. We might want to have it automatically use our production endpoint unless we specify it to use another address. This might look like this:

Press + to interact
qotd

This simply contacts our production server and gets our quote. The --endpoint flag, which defaulted to our production address, will use another address below:

Press + to interact
qotd --endpoint="127.0.0.1:3850"

Sometimes, application arguments will suffice. Take an application that reformats JSON data for human readability. We might want to just read from STDIN if no files are provided. In this case, just reading the values from the command line will suffice using the os package. This will give us executions that look like this:

Press + to interact
reformat file1.json file2.json

Here, we are reading in file1.json and file2.json and ...