Cobra Go CLI Tutorial: Build a Real Shop Orders Tool

Quick answer

Cobra is the Go library behind tools like kubectl, Hugo, and GitHub CLI: you describe each command as a small struct with flags, and Cobra builds the help text, parses the flags, and prints a usage error when a required flag is missing. This post builds a small orders CLI for a shop in Karachi with add, list, and totals commands, real orders, and the first error beginners hit.

A shop in Karachi takes orders over the phone and writes each one in a paper notebook. At the end of the day the owner adds up the totals by hand, and a missed line means sales never match the cash in the drawer. A small terminal tool would fix that: type an order in, list them, and see sales per city. Go ships a flag package for that, but the moment the tool grows a second command, it starts to fight back. Cobra is the library most Go teams reach for instead, and this post builds the tool with it.

What I would check before using it

My first check is whether the tool has more than one command. A single command with one or two flags is fine with Go's built-in flag package: no dependency and the code stays short. The moment it grows a second command, Cobra earns its place, because each command is one small struct with its own flags instead of a switch statement that keeps growing. The Gin Go Tutorial: Build Fast APIs With Very Little Code post shows the same idea on the web side: a little structure up front keeps a growing tool readable.

My second check is who will use the tool. If other developers or the shop owner will run it, a clean --help screen matters, and Cobra generates one from the definitions. It also adds a help command and shell completion for free.

My third check is validation. Cobra marks flags as required and types them, so a missing --total stops the command before any code runs, and text where a number belongs fails at flag parsing. That is the same idea behind the Typer Python CLI Tutorial: Build a Real Orders Tool post, which leans on type hints for the same job.

My fourth check is dependencies. Cobra pulls in pflag and mousetrap, and the result is still one static binary with nothing to install on the target machine, which is the usual reason teams pick Go for command line tools.

My verdict, as judgement: use Cobra for any Go tool with two or more commands, or one command whose flags need validation. Keep the flag package for a one-off script. The recommendation flips if the tool must run with zero third-party dependencies, or if no second command is ever planned.

Four orders, three commands, and one missing flag

Four orders belong to one small shop: Sana in Karachi, Rs 9,800; Daniyal in Lahore, Rs 13,400; Mahnoor in Islamabad, Rs 11,200; Hamza in Karachi, Rs 6,750.

First, set up the module and install Cobra, which also pulls in its flag library pflag and mousetrap. The build then produces one static binary, and --help prints the three commands, plus the completion and help commands Cobra adds for free.

$ go mod init orders
go: creating new go.mod: module orders

$ go get github.com/spf13/cobra
go: downloading github.com/inconshreveable/mousetrap v1.1.0
go: downloading github.com/spf13/pflag v1.0.9
go: added github.com/inconshreveable/mousetrap v1.1.0
go: added github.com/spf13/cobra v1.10.2
go: added github.com/spf13/pflag v1.0.9
$ go build -o orders .

$ ./orders --help
Track shop orders and total sales per city.

Usage:
  orders [command]

Available Commands:
  add         Record one new order.
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  list        Show every order on file.
  totals      Print sales per city and a grand total.

Flags:
  -h, --help   help for orders

Use "orders [command] --help" for more information about a command.

Here is the program, which stores the orders in a JSON file next to the binary. Each command is a cobra.Command with a Use line, a Short line, and a RunE function. The add command marks customer, city, and total as required flags, and it rejects a bad total itself, while totals groups the orders per city. All three commands share one small set of helpers.

// Orders CLI for The Practical Developer (Cobra demo).
//
// A small shop in Karachi takes orders over the phone and stores
// them in a JSON file next to this binary. Three commands:
//   add    - record one order
//   list   - show every order on file
//   totals - sales per city plus a grand total
//
// Build and run from this folder:
//   go build -o orders .
//   ./orders add --customer Sana --city Karachi --total 9800
//   ./orders list
//   ./orders totals
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"sort"

	"github.com/spf13/cobra"
)

const dataFile = "orders.json"

type Order struct {
	ID       int      `json:"id"`
	Customer string   `json:"customer"`
	City     string   `json:"city"`
	Items    []string `json:"items"`
	Total    int      `json:"total"`
}

func loadOrders() ([]Order, error) {
	data, err := os.ReadFile(dataFile)
	if err != nil {
		if os.IsNotExist(err) {
			return []Order{}, nil
		}
		return nil, err
	}
	var orders []Order
	if err := json.Unmarshal(data, &orders); err != nil {
		return nil, err
	}
	return orders, nil
}

func saveOrders(orders []Order) error {
	data, err := json.MarshalIndent(orders, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(dataFile, data, 0644)
}

func main() {
	var customer, city, items string
	var total int

	rootCmd := &cobra.Command{
		Use:   "orders",
		Short: "Track shop orders and total sales per city.",
	}

	addCmd := &cobra.Command{
		Use:   "add",
		Short: "Record one new order.",
		RunE: func(cmd *cobra.Command, args []string) error {
			if total <= 0 {
				return fmt.Errorf("total must be greater than 0")
			}
			orders, err := loadOrders()
			if err != nil {
				return err
			}
			id := 101
			for _, o := range orders {
				if o.ID >= id {
					id = o.ID + 1
				}
			}
			var itemList []string
			if items != "" {
				for _, item := range splitItems(items) {
					itemList = append(itemList, item)
				}
			}
			order := Order{ID: id, Customer: customer, City: city, Items: itemList, Total: total}
			orders = append(orders, order)
			if err := saveOrders(orders); err != nil {
				return err
			}
			fmt.Printf("Order %d added: %s (%s), Rs %d\n", id, customer, city, total)
			return nil
		},
	}
	addCmd.Flags().StringVar(&customer, "customer", "", "Customer name")
	addCmd.Flags().StringVar(&city, "city", "", "City the order ships to")
	addCmd.Flags().IntVar(&total, "total", 0, "Order total in Rs (must be positive)")
	addCmd.Flags().StringVar(&items, "items", "", "Comma separated items")
	_ = addCmd.MarkFlagRequired("customer")
	_ = addCmd.MarkFlagRequired("city")
	_ = addCmd.MarkFlagRequired("total")

	listCmd := &cobra.Command{
		Use:   "list",
		Short: "Show every order on file.",
		RunE: func(cmd *cobra.Command, args []string) error {
			orders, err := loadOrders()
			if err != nil {
				return err
			}
			if len(orders) == 0 {
				fmt.Println("No orders yet.")
				return nil
			}
			for _, o := range orders {
				itemText := "no items listed"
				if len(o.Items) > 0 {
					itemText = joinItems(o.Items)
				}
				fmt.Printf("#%d %s (%s): %s - Rs %d\n", o.ID, o.Customer, o.City, itemText, o.Total)
			}
			return nil
		},
	}

	totalsCmd := &cobra.Command{
		Use:   "totals",
		Short: "Print sales per city and a grand total.",
		RunE: func(cmd *cobra.Command, args []string) error {
			orders, err := loadOrders()
			if err != nil {
				return err
			}
			byCity := map[string]int{}
			for _, o := range orders {
				byCity[o.City] += o.Total
			}
			grandTotal := 0
			for _, v := range byCity {
				grandTotal += v
			}
			fmt.Printf("%d orders on file\n", len(orders))
			cities := make([]string, 0, len(byCity))
			for city := range byCity {
				cities = append(cities, city)
			}
			sort.Strings(cities)
			for _, city := range cities {
				fmt.Printf("  %s: Rs %d\n", city, byCity[city])
			}
			fmt.Printf("Grand total: Rs %d\n", grandTotal)
			if len(orders) > 0 {
				fmt.Printf("Average order: Rs %d\n", grandTotal/len(orders))
			}
			return nil
		},
	}

	rootCmd.AddCommand(addCmd, listCmd, totalsCmd)
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

func splitItems(s string) []string {
	var out []string
	start := 0
	for i := 0; i < len(s); i++ {
		if s[i] == ',' {
			out = append(out, trimSpace(s[start:i]))
			start = i + 1
		}
	}
	out = append(out, trimSpace(s[start:]))
	var kept []string
	for _, item := range out {
		if item != "" {
			kept = append(kept, item)
		}
	}
	return kept
}

func trimSpace(s string) string {
	for len(s) > 0 && (s[0] == ' ' || s[0] == '\t') {
		s = s[1:]
	}
	for len(s) > 0 && (s[len(s)-1] == ' ' || s[len(s)-1] == '\t') {
		s = s[:len(s)-1]
	}
	return s
}

func joinItems(items []string) string {
	out := ""
	for i, item := range items {
		if i > 0 {
			out += ", "
		}
		out += item
	}
	return out
}
$ ./orders add --customer Sana --city Karachi --total 9800 --items "kurta, dupatta"
Order 101 added: Sana (Karachi), Rs 9800
$ ./orders add --customer Daniyal --city Lahore --total 13400 --items sneakers
Order 102 added: Daniyal (Lahore), Rs 13400
$ ./orders add --customer Mahnoor --city Islamabad --total 11200 --items "handbag, wallet"
Order 103 added: Mahnoor (Islamabad), Rs 11200
$ ./orders add --customer Hamza --city Karachi --total 6750 --items "jacket, shalwar kameez"
Order 104 added: Hamza (Karachi), Rs 6750

The numbers check out: Karachi Rs 9,800 plus Rs 6,750 is Rs 16,550, and the four orders add to Rs 41,150.

$ ./orders list
#101 Sana (Karachi): kurta, dupatta - Rs 9800
#102 Daniyal (Lahore): sneakers - Rs 13400
#103 Mahnoor (Islamabad): handbag, wallet - Rs 11200
#104 Hamza (Karachi): jacket, shalwar kameez - Rs 6750

$ ./orders totals
4 orders on file
  Islamabad: Rs 11200
  Karachi: Rs 16550
  Lahore: Rs 13400
Grand total: Rs 41150
Average order: Rs 10287
Terminal output showing a Cobra demo: the orders CLI help listing add, list, and totals, four orders added for a shop in Karachi, totals printing Karachi Rs 16550 and a grand total of Rs 41150, and the error for a missing --total flag.

The thing that went wrong was forgetting a flag: add without --total stops before any code runs, prints a usage error, and exits with code 1. The fix is to pass the missing flag, or drop the MarkFlagRequired call so the flag becomes optional. A mistyped command fails too: lst gave "Error: unknown command "lst" for "orders"" and Cobra even suggested list. A wrong type fails at flag parsing: --total abc gave "Error: invalid argument "abc" for "--total" flag: strconv.ParseInt: parsing "abc": invalid syntax".

Common mistakes and how to fix them

First, forgetting a required flag. The symptom is the usage error "Error: required flag(s) "total" not set" with exit code 1, exactly as the demo showed. The fix is to pass the flag, or remove the MarkFlagRequired call.

Second, typing a command name wrong. The symptom is "Error: unknown command "lst" for "orders"" followed by "Did you mean this? list", also with exit code 1. The fix is to use the exact command name, or check ./orders --help for the list.

Third, passing text where a number belongs. The symptom is "Error: invalid argument "abc" for "--total" flag: strconv.ParseInt: parsing "abc": invalid syntax", with exit code 1. The fix is to pass a number, or change the flag to a string and check it inside RunE.

Fourth, running the binary from the wrong folder. The symptom is list printing "No orders yet." even though orders were added earlier, because orders.json lives next to the binary and is read relative to the working directory. The fix is to cd into the folder holding the binary first.

Frequently Asked Questions

Is Cobra the same as Go's flag package? No. The flag package ships with Go and handles one flat set of flags, while Cobra adds commands, help text, and shell completion on top of it.

Does Cobra work with Viper? Yes. Viper handles configuration files and environment variables, and the two come from the same team, but Cobra does not need Viper to work.

Can Cobra generate shell completion? Yes. Every Cobra program gets a completion command for free, printing a script for bash, zsh, fish, or PowerShell.

Do I need Cobra for a one-command tool? No. One command with one or two flags is simpler with the flag package; Cobra pays off once a second command appears.

What to remember

  • A Cobra command is a small struct with Use, Short, and a RunE function, and flags attach to the command.
  • MarkFlagRequired makes Cobra reject a missing flag before your code runs.
  • Cobra adds help and completion commands for free, and --help lists every command.
  • A mistyped command name gets a "Did you mean this?" suggestion.
  • Orders are stored in a JSON file next to the binary, so run it from the right folder.

Where this leaves you

Cobra earns its place the day a Go script grows a second command and the flag package starts to feel like a switch statement that never ends. The demo proved it: the help text came free from the command definitions, four real orders went in with one short command each, and the missing --total flag failed loudly with exit code 1 instead of writing a broken order to the file. Take a Go script you already run and give it one Cobra command with a required flag. A tool that explains itself beats a script only its author can run.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Comments

Popular posts from this blog

Swift Explained: Apple's Language for iPhone, Mac, and More

LangChain Tutorial: Build Your First LLM App in Python

Rust Explained: Memory Safety Without a Garbage Collector