Tutorial

How to Build a CLI with Cobra in Go

Build a CLI with Cobra in Go so commands, flags, and help are declarative, and completion is generated automatically.

On this page

  1. Introduction
  2. Define the root command
  3. Add subcommands
  4. Set flags
  5. Generate help
  6. Add completion
  7. Test the CLI
  8. Common pitfalls
  9. Conclusion

Introduction

The hardest part of build Go CLI is not writing the code — it is deciding what the code is allowed to reject. A Cobra setup that accepts everything is easy to ship and expensive to operate, because every malformed input becomes a production surprise. The discipline is to enumerate the shapes the system actually receives, encode them in Cobra, and let the library reject the rest loudly. This keeps the happy path fast and the failure path visible.

A Cobra guard for build Go CLI should be proportional to the risk. A ten-field form does not need a hundred-line schema; it needs the five checks that catch the five mistakes the users actually make. Ship the five, measure the rejections, and add the sixth only when the traffic proves it exists. Speculative generality is the bug you write on purpose, and Cobra makes it easy to write, which is why discipline matters.

The sections below walk through the concrete decisions: where to put the cobra check, how to keep it fast under load, what to do when the contract changes, and how to test the failure paths so they degrade on purpose instead of by accident.

Define the root command

Define the root command is the first decision because it determines what the rest of the Cobra pipeline can assume. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Define the root command is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

var root = &cobra.Command{ Use: "mycli", Short: "my CLI" }
var build = &cobra.Command{ Use: "build", Run: func(c *cobra.Command, a []string) { build() } }
root.AddCommand(build)
root.Execute()

The go above is the shape to ship for build Go CLI. It is small enough to audit and specific enough that the failure behavior is obvious. Adapt the constants to your traffic and latency budget, and resist the urge to handle cases the system has not seen yet.

Add subcommands

The mechanism behind Add subcommands is straightforward in Cobra, but the consequences ripple. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Add subcommands is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Set flags

Set flags is where most Cobra implementations leak performance. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Set flags is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

func TestBuild(t *testing.T) {
  root.SetArgs([]string{"build"})
  root.Execute()
  // assert build ran
}

Pin the behavior with this test. A Cobra setup that passes this test degrades on purpose instead of by accident, which is the difference between a managed failure and an incident.

Generate help

The hard part of Generate help is not the happy path — it is what happens when cobra fails halfway. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Generate help is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Add completion

Add completion should be observable without a debugger. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Add completion is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Test the CLI

Test the CLI is a trade, not a winner. A wrong choice here turns into build Go CLI under load, and the invariant you thought Cobra guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Test the CLI is the one most teams skip: drive cobra to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Common pitfalls

The common pitfalls in build Go CLI all reduce to one mistake: treating Cobra as a formality instead of a contract. The contract is the thing the rest of the system relies on, and a weak contract propagates weakness everywhere.

  • Skipping the cobra boundary so build Go CLI enters unvalidated.
  • Assuming Cobra is fast without measuring the tail latency under load.
  • Letting build Go CLI fail silently instead of failing loudly with a metric.
  • Testing only the happy path so the cobra failure surfaces in production.
  • Sharing mutable state across requests so one bad input poisons the next.

Conclusion

Do not conflate the conclusion with the implementation. They look similar from the outside but the failure modes differ: Cobra fails fast and the caller knows, while an unchecked path fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site.

Self-check: write a test that drives cobra to the failing condition and assert the system degrades gracefully. Then build Go CLI is a property you maintain, not a feature you hope for.

Sources: Cobra, Go CLI

FAQ

Why Cobra?
It is the standard Go CLI lib. Help, completion, and flags are built in.
Viper for config?
Yes. Cobra and Viper are designed to work together.

Related Examples