Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
48: Working with Environment Variables and Flags
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
flagpackage. These are perfect for things you change often while testing, like a-portnumber or a-verbosemode.
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 to3) 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."
There are no comments for now.