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
156: Defining Flags with the flag Package
You've probably written a few CLI tools by now, and you've likely relied on os.Args to grab some quick input. But as soon as you need something more complex—like optional settings, default values, or a --help menu—parsing a raw string slice becomes a nightmare. That's where the flag package comes in. It's the standard way to handle command-line arguments in Go without pulling in a massive third-party library.
Setting up a simple log filter
Let's build a small utility that filters a log file based on a specific search term. I want to be able to tell the program which file to look at and what keyword to search for. In my head, I want the command to look like this: go run main.go -file=app.log -term=ERROR.
Here is how I'll start. I'll use flag.String, which returns a pointer to a string. This is a crucial detail—the value isn't available immediately; it's populated once the flags are parsed.
package main
import (
"flag"
"fmt"
)
func main() {
// Define a string flag: name, default value, and usage description
filePath := flag.String("file", "system.log", "The path to the log file")
searchTerm := flag.String("term", "WARN", "The keyword to filter by")
fmt.Printf("Searching in %s for %s...\n", *filePath, *searchTerm)
}
Wait, why aren't my flags changing?
If I run this right now with -file=test.log -term=CRITICAL, I'll notice something frustrating: the program ignores my input and prints "Searching in system.log for WARN...".
I've made this mistake a dozen times. I defined the flags, but I forgot to actually tell Go to look at the command-line arguments and assign them to those pointers. In the flag package, nothing happens until you call flag.Parse(). It's a common trip-up, but it's the most important line in the whole process.
func main() {
filePath := flag.String("file", "system.log", "The path to the log file")
searchTerm := flag.String("term", "WARN", "The keyword to filter by")
// This is the missing piece!
flag.Parse()
fmt.Printf("Searching in %s for %s...\n", *filePath, *searchTerm)
}
Handling numbers and toggles
A real tool usually needs more than just strings. I want to add a limit to how many lines we process (an integer) and a "verbose" mode (a boolean). For integers, I'll use flag.Int, and for booleans, flag.Bool.
Notice that I'm using pointers for all of these. If you prefer to have the value stored in an existing variable instead of getting a pointer back, you can use flag.StringVar or flag.IntVar. I personally prefer the pointer method for simple tools because it's more concise.
package main
import (
"flag"
"fmt"
)
func main() {
filePath := flag.String("file", "system.log", "The path to the log file")
searchTerm := flag.String("term", "WARN", "The keyword to filter by")
maxLines := flag.Int("limit", 100, "Max lines to scan")
verbose := flag.Bool("v", false, "Enable verbose logging")
flag.Parse()
fmt.Printf("Settings: File=%s, Term=%s, Limit=%d, Verbose=%v\n",
*filePath, *searchTerm, *maxLines, *verbose)
}
One cool thing that happens automatically here: if you run your program with -h or --help, Go will generate a perfectly formatted help menu using those description strings I provided. You don't have to write a single line of code for that.
📋 Practical Task
Build a Network Port Scanner Configuration
Create a CLI tool that simulates a port scanner. You don't need to implement the actual network scanning logic, but you must implement the flag parsing to accept the following configuration:
- A string flag
-host(default: "localhost") - An integer flag
-port(default: 80) - A boolean flag
-timeout(default: false) to indicate if a custom timeout should be applied
Your program should parse these flags and print a summary like: "Scanning host localhost on port 80 (Timeout enabled: false)". Make sure you handle the pointers correctly and remember to call the necessary function to process the arguments.
There are no comments for now.