Stage 3 · Build
Building CLI Tools
Output Formats
Table, JSON, YAML, and templating with Go templates for flexible CLI output.
Format Selection Pattern
Most SRE tools support multiple output formats. The standard pattern is a --output flag that selects table, JSON, YAML, or a custom template. This lets users pipe output to jq, yq, or other tools.
Table Output
Tables are the default output format for human-readable CLI output. Use text/tabwriter or a table library for aligned columns.
JSON Output
JSON output is essential for piping to jq and integrating with other tools. Use encoding/json with proper indentation for readability.
json.Encoder writes directly to a Writer without allocating a string. For large outputs, this is significantly more memory-efficient than json.Marshal followed by fmt.Println.
YAML Output
YAML output is useful for Kubernetes-related tools where users paste results into YAML files. Use gopkg.in/yaml.v3 for consistent formatting.
Go Templates
Go templates let users define custom output formats. The --format flag accepts a template string, and the tool renders it against the data.
Colorizing Output
Color makes output scannable — green for healthy, red for error, yellow for warning. Use lipgloss or color for terminal colors with automatic detection.
Use the same --output flag name and the same format options across all commands. Users should not have to guess whether a command supports JSON output. Document the supported formats in the command help.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.