Skip to content

Quick Start

Create a main.go with typed flags, a command, and proper exit codes:

package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
)
type AppConfig struct {
Verbose bool `flag:"verbose" short:"v" default:"false" help:"Enable verbose output"`
Output string `flag:"output" short:"o" default:"text" help:"Output format"`
}
type GreetFlags struct {
Name string `flag:"name" short:"n" default:"World" help:"Name to greet"`
Shout bool `flag:"shout" short:"s" default:"false" help:"Uppercase output"`
}
func main() {
cli, err := v5.NewCLI[AppConfig]("myapp", "My CLI application", AppConfig{})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create CLI: %v\n", err)
os.Exit(1)
}
greetCmd, err := v5.NewCommand("greet", GreetFlags{},
func(ctx context.Context, cfg *AppConfig, flags GreetFlags) error {
msg := fmt.Sprintf("Hello, %s!", flags.Name)
if flags.Shout {
msg = strings.ToUpper(msg)
}
fmt.Println(msg)
return nil
},
v5.WithShort("Greet someone"),
)
b := v5.NewBuilder(cli)
v5.Try(b, greetCmd, err)
if err := b.Build(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to register command: %v\n", err)
os.Exit(1)
}
cli.ExecuteAndExit(context.Background())
}
Terminal window
$ go run main.go greet -n "cmdguard" --shout
HELLO, CMDGUARD!
  1. NewCLI[AppConfig] — created the root CLI with your config struct as a type parameter. In v5 the production batteries are ON by default: strict command validation, signal handling with graceful DI shutdown, strict config keys, actionable error hints, and auto-registered doctor (plus version when a CLI version is set). Each has a Without* opt-out.
  2. NewCommand("greet", GreetFlags{}, handler) — created a command with its own typed flag struct (by value, parsed into the handler’s third parameter)
  3. NewBuilder + Try + Build() — the v5 registration path: constructor errors are collected (no error ladder) and Build() attaches atomically
  4. ExecuteAndExit(ctx) — ran the CLI and exited with the correct code

Group related commands under a parent:

listCmd, _ := v5.NewCommand("list", v5.NoFlags{}, listHandler,
v5.WithShort("List users"),
)
createCmd, _ := v5.NewCommand("create", v5.NoFlags{}, createHandler,
v5.WithShort("Create a user"),
)
userCmd, _ := v5.NewParentCommand[AppConfig]("user",
"User management", v5.NoFlags{},
v5.WithSubcommands(listCmd, createCmd),
v5.WithShort("User management"),
)
v5.AddCommand(cli, userCmd)

Migrating from v4? Run the codemod — it rewrites module paths, import aliases, and the renames mechanically.