Lab 13: CLI with Cobra

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Build a fully-featured CLI application using Cobraarrow-up-right — the same framework powering kubectl, docker, and hugo. Add Viper for config management, subcommands, and shell completion.


Step 1: Project Setup

mkdir mycli && cd mycli
go mod init mycli
go get github.com/spf13/cobra@latest
go get github.com/spf13/viper@latest

Directory structure:

mycli/
├── main.go
├── cmd/
│   ├── root.go
│   ├── serve.go
│   └── version.go
└── go.mod

💡 Cobra conventionally places each command in its own file under cmd/. This keeps each command self-contained and testable.


Step 2: Root Command with Persistent Flags

cmd/root.go:


Step 3: serve Subcommand

cmd/serve.go:


Step 4: version Subcommand

cmd/version.go:


Step 5: Positional Args Validation

Add a greet subcommand that requires exactly one positional argument:

💡 Cobra provides: cobra.NoArgs, cobra.ExactArgs(n), cobra.MinimumNArgs(n), cobra.MaximumNArgs(n), cobra.RangeArgs(min, max).


Step 6: Shell Completion

Cobra generates shell completion automatically:

The completion command is registered automatically when you call rootCmd.Execute().


Step 7: Viper Config File Integration

config.yaml (auto-loaded from .):

Priority order (highest → lowest):

  1. Explicit --flag value

  2. Environment variable (MYCLI_SERVER_PORT)

  3. Config file (config.yaml)

  4. viper.SetDefault()


Step 8 (Capstone): Full CLI Demo

Simulated CLI behavior (Docker-runnable without network):

📸 Verified Output:


Summary

Concept
Cobra API
Purpose

Command definition

cobra.Command{Use, Short, Long, RunE}

Define CLI commands

Persistent flags

PersistentFlags().StringVar/BoolVar/IntVar

Flags shared by all subcommands

Local flags

Flags().IntP("port", "p", 8080, ...)

Flags scoped to one command

Subcommands

rootCmd.AddCommand(serveCmd)

Hierarchical commands

Config management

viper.SetDefault/GetString/BindPFlag

File + env + flag merging

Args validation

cobra.ExactArgs(n)

Enforce positional arg count

Shell completion

mycli completion bash

Auto-generated completions

Last updated