Increasing Flexibility with Environment Variables

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Improving the List Output Forma t | TOC | Capturing Input from STDIN 👉

With all the improvements you made to your to-do tool so far, you’ve provided your users with several useful features. But the user still can’t select which file to save to the list of to-do items. You could use different approaches in this situation, such as adding another flag to allow the user to specify the file name, but another way to make your tool more flexible is by using environment variables.

Using environment variables allows your users to specify options once in their shell configuration, which means the user avoids typing that option for every command execution. It also lets the user have different configurations for different environments.

In Go, the os package provides functions to handle both the environment and environment variables. We’ll use the function os.Getenv(“TODO_FILENAME”) to retrieve the value of the environment variable identified by the name TODO_FILENAME.

To add this feature to your to-do tool, make two changes to the main.go file. First, update the line where you define the todoFileName from a constant to a variable so it can be changed later in case the environment variable is defined. This line works as the default file name when the user doesn’t set the environment variable:

--

--

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.