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
57: Building a CLI Tool with Cobra
How do I actually get a project started without wiring every command by hand?
If you've tried building a CLI using just the standard flag package, you know it gets messy fast once you have subcommands. That's why we use Cobra. I usually start by installing the cobra-cli tool; it handles the boilerplate so you don't have to spend an hour creating folders and initializing root commands.
For this lesson, let's imagine we're building taskmaster, a tool to manage a local JSON-based todo list. After installing the CLI tool, I'd run cobra-cli init. This generates a cmd/root.go file. This is your entry point. It defines the base command that every other command will hang off of.
// cmd/root.go
var rootCmd = &cobra.Command{
Use: "taskmaster",
Short: "Taskmaster manages your daily grind",
Long: `A simple CLI tool to track tasks in a local JSON file.`,
Run: func(cmd *cobra.Command, args []string) {
// This runs if no subcommand is provided
fmt.Println("Welcome to Taskmaster! Use 'taskmaster add' to get started.")
},
}
Once that's set, adding a new action is as simple as cobra-cli add add. This creates cmd/add.go, which is automatically registered to the root command. It's a much cleaner way to scale your tool as you add more features.
What's the deal with Persistent Flags versus Local Flags?
This is where people usually get tripped up. In Cobra, a Persistent Flag is available to the command it's assigned to AND every subcommand under it. A Local Flag only works for that specific command.
Think about our taskmaster tool. You might want to specify the path to your JSON database file. Since every single command (add, list, delete) needs to know where that file is, that should be a persistent flag on the root command. However, a --priority flag only makes sense when you're adding a task, so that's a local flag.
// In cmd/root.go
var cfgFile string
func init() {
// Every subcommand can now access --config
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "tasks.json", "config file for tasks")
}
// In cmd/add.go
var priority string
func init() {
// Only 'taskmaster add' can use --priority
addCmd.Flags().StringVarP(&priority, "priority", "p", "medium", "priority level (low, medium, high)")
}
I personally prefer using StringVarP (the 'P' version) because it lets you define both a long flag (--priority) and a short shorthand (-p), which makes the tool feel way more professional for the end user.
How do I keep my cmd folder from becoming a giant mess of spaghetti?
I've seen too many Go projects where the entire business logic is crammed inside the Run function of the Cobra command. Please, don't do that. The cmd package should be a thin wrapper. Its only jobs are to parse flags, validate the input, and call a function in another package.
If you put your JSON parsing and file writing logic directly in add.go, you'll find it impossible to write unit tests for that logic without simulating a full CLI execution. Instead, create a internal/tasks package to handle the actual data work.
// cmd/add.go
var addCmd = &cobra.Command{
Use: "add [task]",
Short: "Add a new task to the list",
Args: cobra.MinimumNArgs(1), // Validates that the user actually provided a task name
Run: func(cmd *cobra.Command, args []string) {
taskName := args[0]
// Delegate the actual work to a separate package
err := tasks.AddTask(cfgFile, taskName, priority)
if err != nil {
log.Fatalf("could not add task: %v", err)
}
fmt.Printf("Added task: %s [%s]\n", taskName, priority)
},
}
By keeping the Run function lean, your CLI becomes a delivery mechanism, not the application itself. This makes your code modular and actually maintainable.
📋 Practical Task
Exercise: Implement Task Filtering for Taskmaster
Now it's your turn to extend the taskmaster tool. You need to create a list command that allows users to view their tasks, but with a twist: they should be able to filter the list by priority using a flag.
- Use
cobra-cli add listto generate the command. - Add a local flag
--filter(with a shorthand-f) to thelistcommand. - Ensure the command validates that no positional arguments are passed (use
cobra.NoArgs). - In the
Runfunction, print a message indicating which priority is being filtered (e.g., "Filtering tasks by priority: high"). If no filter is provided, it should say "Showing all tasks".
There are no comments for now.