Skip to Content
Course content

48: Working with Environment Variables and Flags

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of running a piece of software like ordering a meal at a restaurant. Most of the time, the kitchen has "house rules"—the general way things are done, like the default salt level or the temperature of the room. These are like environment variables. They are set once for the environment, and every order (or process) that happens in that kitchen inherits those rules without you having to mention them every single time.

Now, imagine you want your specific burger medium-rare instead of well-done. You don't change the house rules for the whole restaurant; you just add a specific request to your order. That's a command-line flag. It's a one-time override used specifically for that one execution of the program.

In Go, we map these two concepts like this:

  • House Rules (Env Vars)os.Getenv("KEY"). These are great for secrets (like API keys) or settings that stay the same across a whole server deployment.
  • Special Requests (Flags) → The flag package. These are perfect for things you change often while testing, like a -port number or a -verbose mode.

Plucking values from the system

Environment variables are basically a giant map of strings stored by the operating system. In Go, the os package is your gateway. I usually use these for things I absolutely do not want to commit to GitHub, like database passwords.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Look for a variable named "API_KEY"
	apiKey := os.Getenv("API_KEY")

	if apiKey == "" {
		fmt.Println("Warning: API_KEY is not set. The app might not authenticate.")
	} else {
		fmt.Printf("Authenticated with key: %s...\n", apiKey[:4]) 
	}
}

One thing to remember: os.Getenv returns an empty string if the variable isn't there. If you need to distinguish between "it's empty" and "it's not set at all," you'll want to use os.LookupEnv, which returns a boolean as a second value. I personally find LookupEnv much safer for critical configuration.

Giving your tool a set of knobs

While environment variables are passive, flags are active. You define them at the start of your main function, and Go handles the parsing of os.Args for you. Let's build a small utility that simulates a log processor. We want to be able to specify the log file path and whether we want "debug" mode on.

package main

import (
	"flag"
	"fmt"
)

func main() {
	// Define a string flag: name, default value, and description
	filePath := flag.String("file", "app.log", "Path to the log file to analyze")
	
	// Define a boolean flag: name, default value, and description
	debugMode := flag.Bool("debug", false, "Enable verbose logging output")

	// This is the most important line. If you forget this, 
	// the flags will never be parsed!
	flag.Parse()

	fmt.Printf("Analyzing file: %s\n", *filePath)
	if *debugMode {
		fmt.Println("Debug mode is ON. Showing all internal traces...")
	}
}

Notice that flag.String and flag.Bool return pointers (*string and *bool). This is because the flag package needs to update the value after flag.Parse() is called. That's why I used *filePath to get the actual value. It's a common stumbling block for people new to the package.

Mixing both for a professional setup

In a real production app, you rarely choose just one. I typically follow this hierarchy: Flags override Environment Variables, and Environment Variables override Hardcoded Defaults. It gives the user the most flexibility.

Imagine a tool that connects to a database. You'd put the DB_PASSWORD in an environment variable (for security) but let the -timeout be a flag (for quick tuning). If you find yourself writing a massive if/else chain to handle this, just create a simple Config struct and a function to populate it. It keeps your main function from becoming a cluttered mess of configuration logic.




📋 Practical Task

Building a Configurable API Health Checker

Your task is to create a CLI tool that simulates checking the health of a remote API. The tool must implement the following requirements:

  • Environment Variable: It must look for an environment variable called API_TOKEN. If it's missing, the program should print "Error: API_TOKEN is required" and exit.
  • String Flag: It must have a flag called -url (defaulting to "https://api.example.com") that specifies which endpoint to check.
  • Integer Flag: It must have a flag called -retries (defaulting to 3) that specifies how many times to attempt the connection.

When run, the program should print a summary like: "Checking https://api.example.com with token [first 3 chars of token]... Retrying up to 3 times."

Rating
0 0

There are no comments for now.

to be the first to leave a comment.