TExcelTAD

Go CLIs with flag

The standard flag package parses command-line options with typed values, defaults and generated help. It is deliberately small: single-dash and double-dash forms are equivalent (-env prod, --env=prod), options must come before positional arguments, and there are no short/long pairs. For most internal tools that is enough; when it is not, Cobra (used by kubectl, helm, gh) is the usual next step.

A FlagSet with typed options

flag.Parse() reads os.Args. A flag.FlagSet parses any slice you give it, which is how you test a CLI, and how these examples run with fixed arguments:

go · try it yourself
package main

import (
	"flag"
	"fmt"
	"os"
	"strings"
	"time"
)

type config struct {
	env      string
	replicas int
	timeout  time.Duration
	dryRun   bool
	services []string
}

func parse(args []string) (config, error) {
	var c config
	fs := flag.NewFlagSet("scale", flag.ContinueOnError)
	fs.SetOutput(os.Stdout) // usage and errors; os.Stderr in a real tool
	fs.StringVar(&c.env, "env", envOr("DEPLOY_ENV", "dev"), "target environment ($DEPLOY_ENV overrides the default)")
	fs.IntVar(&c.replicas, "replicas", 2, "number of replicas")
	fs.DurationVar(&c.timeout, "timeout", 30*time.Second, "how long to wait for rollout")
	fs.BoolVar(&c.dryRun, "dry-run", false, "print the plan only")
	if err := fs.Parse(args); err != nil {
		return c, err
	}
	c.services = fs.Args() // positional arguments after the flags
	if len(c.services) == 0 {
		return c, fmt.Errorf("at least one service is required")
	}
	return c, nil
}

func envOr(key, def string) string {
	if v, ok := os.LookupEnv(key); ok {
		return v
	}
	return def
}

func main() {
	for _, args := range [][]string{
		{"shop-api"},
		{"-env", "prod", "--replicas=6", "-timeout", "2m30s", "-dry-run", "shop-api", "worker"},
		{"-replicas", "six", "shop-api"},
	} {
		fmt.Printf("$ scale %s\n", strings.Join(args, " "))
		c, err := parse(args)
		if err != nil {
			fmt.Println("error:", err, "-> exit 2")
			continue
		}
		fmt.Printf("env=%s replicas=%d timeout=%s dryRun=%v services=%v\n", c.env, c.replicas, c.timeout, c.dryRun, c.services)
	}
}
$ scale shop-api
env=dev replicas=2 timeout=30s dryRun=false services=[shop-api]
$ scale -env prod --replicas=6 -timeout 2m30s -dry-run shop-api worker
env=prod replicas=6 timeout=2m30s dryRun=true services=[shop-api worker]
$ scale -replicas six shop-api
invalid value "six" for flag -replicas: parse error
Usage of scale:
  -dry-run
    	print the plan only
  -env string
    	target environment ($DEPLOY_ENV overrides the default) (default "dev")
  -replicas int
    	number of replicas (default 2)
  -timeout duration
    	how long to wait for rollout (default 30s)
error: invalid value "six" for flag -replicas: parse error -> exit 2
  • time.Duration flags accept 30s, 2m30s, 1h: no hand-written parsing of "seconds or minutes".
  • With ContinueOnError, Parse returns an error after printing it with the usage; ExitOnError (what the global flag.Parse uses) exits with status 2, the same usage-error convention as in Bash and argparse.
  • The environment provides the default, and the flag overrides it, as in the earlier lessons.

Repeatable and custom flags

Any type that implements flag.Value (String() string and Set(string) error) can be a flag. Here, a repeatable -label key=value option that validates its input:

go · try it yourself
package main

import (
	"flag"
	"fmt"
	"os"
	"sort"
	"strings"
)

type labels map[string]string

func (l labels) String() string {
	keys := make([]string, 0, len(l))
	for k := range l {
		keys = append(keys, k)
	}
	sort.Strings(keys) // Go does not keep map order: sort before printing
	parts := make([]string, len(keys))
	for i, k := range keys {
		parts[i] = k + "=" + l[k]
	}
	return strings.Join(parts, ",")
}

func (l labels) Set(s string) error {
	k, v, ok := strings.Cut(s, "=")
	if !ok || k == "" {
		return fmt.Errorf("want key=value, got %q", s)
	}
	l[k] = v
	return nil
}

func main() {
	fs := flag.NewFlagSet("tag", flag.ContinueOnError)
	fs.SetOutput(os.Stdout)
	lbl := labels{}
	fs.Var(lbl, "label", "a key=value label (repeatable)")

	if err := fs.Parse([]string{"-label", "team=core", "-label", "tier=api", "-label", "team=platform"}); err == nil {
		fmt.Println("labels:", lbl)
	}
	fmt.Println("---")
	if err := fs.Parse([]string{"-label", "oops"}); err != nil {
		fmt.Println("-> exit 2")
	}
	fmt.Println("--- help")
	fs.PrintDefaults()
}
labels: team=platform,tier=api
---
invalid value "oops" for flag -label: want key=value, got "oops"
Usage of tag:
  -label value
    	a key=value label (repeatable)
-> exit 2
--- help
  -label value
    	a key=value label (repeatable)

Two Go habits are visible: map iteration order is random, so anything printed from a map is sorted first, and errors are values (Set returns one, and flag reports it with the flag's name).

Subcommands

flag has no subcommands, but a switch on the first argument with one FlagSet per command is all you need:

go · try it yourself
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"strings"
)

func run(args []string, out io.Writer) int {
	if len(args) < 1 {
		fmt.Fprintln(out, "usage: opsctl <list|scale> [flags]")
		return 2
	}
	switch args[0] {
	case "list":
		fs := flag.NewFlagSet("list", flag.ContinueOnError)
		fs.SetOutput(out)
		all := fs.Bool("all", false, "include archived services")
		if fs.Parse(args[1:]) != nil {
			return 2
		}
		fmt.Fprintf(out, "listing services (all=%v)\n", *all)
	case "scale":
		fs := flag.NewFlagSet("scale", flag.ContinueOnError)
		fs.SetOutput(out)
		n := fs.Int("replicas", 1, "replica count")
		if fs.Parse(args[1:]) != nil {
			return 2
		}
		if fs.NArg() != 1 {
			fmt.Fprintln(out, "usage: opsctl scale -replicas N SERVICE")
			return 2
		}
		fmt.Fprintf(out, "scaling %s to %d\n", fs.Arg(0), *n)
	default:
		fmt.Fprintf(out, "unknown command %q\n", args[0])
		return 2
	}
	return 0
}

func main() {
	for _, args := range [][]string{{"list"}, {"list", "-all"}, {"scale", "-replicas", "3", "worker"}, {"scale", "worker", "-replicas", "3"}, {"deploy"}} {
		fmt.Println("$ opsctl", strings.Join(args, " "))
		fmt.Println("-> exit", run(args, os.Stdout))
	}
}
$ opsctl list
listing services (all=false)
-> exit 0
$ opsctl list -all
listing services (all=true)
-> exit 0
$ opsctl scale -replicas 3 worker
scaling worker to 3
-> exit 0
$ opsctl scale worker -replicas 3
usage: opsctl scale -replicas N SERVICE
-> exit 2
$ opsctl deploy
unknown command "deploy"
-> exit 2

The fourth call shows flag's main limitation: parsing stops at the first positional argument, so scale worker -replicas 3 leaves -replicas 3 as extra arguments and the command rejects it. Cobra and spf13/pflag (GNU-style --long/-s flags, interspersed with arguments) lift that limit:

go
// With Cobra: commands, flags anywhere, generated help and shell completion
var replicas int
var scaleCmd = &cobra.Command{
	Use:   "scale SERVICE",
	Short: "Change the replica count",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		fmt.Printf("scaling %s to %d\n", args[0], replicas)
		return nil
	},
}

func init() {
	scaleCmd.Flags().IntVarP(&replicas, "replicas", "r", 1, "replica count")
	rootCmd.AddCommand(scaleCmd)
}

Test yourself

Why do the examples use flag.NewFlagSet(..., flag.ContinueOnError) instead of flag.Parse()?

  1. flag.Parse is deprecated
  2. A FlagSet parses any argument slice and returns errors, so the CLI can be tested and run with fixed arguments
  3. FlagSets are faster
  4. flag.Parse cannot read integers

With the standard flag package, what happens to -replicas 3 in opsctl scale worker -replicas 3?

  1. It is parsed normally
  2. Parsing stops at worker, so -replicas 3 become positional arguments
  3. It is an error in Go syntax
  4. It sets replicas to worker

Why does the labels type sort its keys in String()?

  1. flag requires sorted output
  2. Go randomises map iteration order, so unsorted output would differ between runs
  3. Sorting validates the keys
  4. To remove duplicates