Skip to Content
Course content

156: Defining Flags with the flag Package

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

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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.