Skip to content

Examples

The repository’s _examples/ directory holds 33 runnable programs, 01 to 32 and 99. Each has its own README and an end-to-end test suite. The suites assert CONGA’s exit codes: 0 for success, including --help and --version, 2 for usage errors, and 1 for schema, configuration, and runtime failures.

Run an example from the repository root:

Terminal window
$ go run ./_examples/01-minimal-hello --name Alice
Hello, Alice!

Run every example’s tests:

Terminal window
go test ./_examples/[0-9]*

Each entry below says what the program does, shows one or more runs, and lists the API it demonstrates: types and interfaces in PascalCase, struct tag keys in lowercase, and methods as Type.Method. Find an example by API indexes those lists.

Most examples print a table of resolved values and where each came from. The runs below keep that table’s header and the rows that matter, or leave the table out. After a failing run, go run adds its own exit status N line, which the blocks leave out.

Source · Tutorial: Quickstart

A greeter with one command. --name (-n) falls back to World, --loud (-l) prints in capitals, and the help screen is generated from the struct.

Default
$ go run ./_examples/01-minimal-hello
Hello, World!

Uses: OptionalFlag[T], default, short

Source · Guide: How to declare flags

Flags of type string, bool, int, float64 and time.Duration, plus a -v counter. -vvv counts to 3, --dbg is an alias of --debug, --secret-key is left out of help, and the flags sit under help sections. A malformed duration is a usage error.

Counter and alias
$ go run ./_examples/02-flag-primitives -vvv --dbg
FIELD TYPE VALUE SOURCE
-v, --verbosity conga.Counter 3 ● cli --verbosity
-d, --debug bool true ● cli --debug

Uses: Counter, aliases, hidden, section

Source · Guide: How to declare flags

--color also takes a --no-color form, and the last one given wins. -e collects KEY=VALUE pairs into a map[string]string. -H keeps the commas inside a value because its slice is declared with sep:"none".

Negation and map
$ go run ./_examples/03-negatable-and-maps --no-color -e A=1 -e B=2
FIELD TYPE VALUE SOURCE
-C, --color bool false ● cli --color
-e, --env-vars map[string]string A=1, B=2 ● cli --env-vars

Uses: negatable, map[K]V, items, sep

Source · Guides: How to read files and standard input, How to add custom flag types

Flags typed as files, directories, byte sizes, and two custom types. --input-file must name an existing file, --max-memory reads 2GiB, and --ports parses and checks a PortRange. Each failure is a usage error.

Valid
$ go run ./_examples/05-domain-types -i go.mod -m 2GiB -p 8000-8080 -H Accept=text/html
FIELD TYPE VALUE SOURCE
-i, --input-file conga.File go.mod ● cli --input-file
-m, --max-memory conga.ByteSize 2GiB ● cli --max-memory
-p, --ports main.PortRange 8000-8080 ● cli --ports
-H, --headers main.HeaderMap Accept=text/html ● cli --headers
Validated Domain Types: max_memory_bytes=2147483648

Uses: File, Dir, ByteSize, FileContent, SelfValidator, existing, stdin, stdout, symlink, glob

Source · Guides: How to use the network, system, and timezone packages, How to add custom flag types

Flags of the standard library types *time.Location and syscall.Signal, which App.Use adds through the timezone and system packages, and a custom Percent type added with App.RegisterType.

Standard library types
$ go run ./_examples/21-pluggable-types -z Europe/Berlin -s HUP
FIELD TYPE VALUE SOURCE
-z, --tz *time.Location Europe/Berlin ● cli --tz
-s, --signal syscall.Signal hangup ● cli --signal

Uses: App.Use, timezone.RegisterLocation, system.RegisterSignal, App.RegisterType, WithPredictor

Source · Guide: How to accept positional arguments

A notifier with a required <channel>, an optional [message], and a trailing [recipients...] slice that takes every remaining word. Leaving out the channel is a usage error.

All arguments
$ go run ./_examples/04-positional-args email 'build failed' oncall pager
FIELD TYPE VALUE SOURCE
<channel> string email ● cli
[message] string build failed ● cli
[recipients...] []string [oncall, pager] ● cli
Broadcast: channel=email message="build failed" urgent=false extra_recipients=2

Uses: RequiredArg[T], OptionalArg[T], OptionalArg.GetOr, name

Source · Guide: How to accept positional arguments

Two ways to hand arguments to another program. test forwards whatever follows --. exec forwards everything after the container name, flags included, with no --.

After --
$ go run ./_examples/11-trailing-args-forwarding test ./pkg/server -- -v -run TestAuth
FIELD TYPE VALUE SOURCE
<pkg> string ./pkg/server ● cli
[-- <args...>] DashArgs -v -run TestAuth ● cli
DashArgs container: [-v -run TestAuth]

Uses: DashArgs, RawArgs

Source · Guide: How to declare subcommands

A service-management CLI whose create, delete and list commands sit under Lifecycle and Inspection headings in help. delete also answers to rm and del, a hidden doctor command still runs, and a mistyped command gets a suggestion.

Typo
$ go run ./_examples/08-subcommands-basic delte
Error:subcommands-basic: error: unknown command: delte (did you mean "delete"?)

Uses: Command[T], aliases, section, hidden, summary

Source · Guide: How to declare subcommands

A fleet tool four commands deep (cluster node pod list). The leaf command reads every ancestor’s flags by walking down from the root. The pod subtree reads FLEET_POD_* variables instead of the FLEET_* prefix the rest of the tool uses.

Deep path
$ go run ./_examples/09-deep-hierarchy-context cluster node pod list -s pending
=== Deep Hierarchy Resolution ===
Full Command Path: deep-hierarchy-context cluster node pod list
Active Leaf Name: list
Root Global Region: us-east-1
Ancestor Cluster: default-cluster
Ancestor Node: node-01
Parent Pod Wait: 5s
Leaf Status Filter: pending

Uses: Session.Root, Command[T].Get, Session.Path, Session.Name, envprefix, App.EnvPrefix

Source · Guide: How to declare subcommands

A script runner where a bare file path runs the run command, so implicit-command ./script.ts and implicit-command run ./script.ts do the same thing. Naming the sibling install still selects install, and help marks run as (default).

Shorthand
$ go run ./_examples/32-implicit-command ./script.ts
run file=script.ts dry-run=false args=[]

Uses: Command[T], implicit, name

Source · Guide: How to validate input

An API client whose flags carry declared limits. --json, --yaml and --table exclude each other, --password needs at least 8 characters, and --port, --timeout and --memory have ranges. A violation is a usage error, and this program prints the full help screen after it.

Exclusive flags
$ go run ./_examples/06-flag-constraints -k secret --json --yaml
Error:flag-constraints: error: flags --json and --yaml are mutually exclusive
Declarative safety constraints (XOR, And, Range, Len, Items, Enum)
Usage:
flag-constraints --api-key=STRING [flags]
Flags:
--json Output in JSON format [xor: --yaml, --table]
--yaml Output in YAML format [xor: --json, --table]
--table Output in Table format [xor: --json, --yaml]
-k, --api-key=STRING API key for authentication (required)
-u, --username=STRING Authentication username [len: 3..20] [and: --password]
--password=STRING Authentication password [len: >= 8] [and: --username]
-p, --port=8080 Port number [1..65535]
--timeout=2s Request timeout [100ms..5s]
--memory=256MiB Byte size (e.g., 10MiB, 1.5GB, 500KiB) [1MiB..1GiB]
--env="dev" Deployment environment [enum: dev, staging, prod]
-z, --zones=STRING,... Availability zones [items: 2..3]
--completion=SHELL Generate shell completion script
--help Show help
--version Show version

Uses: RequiredFlag[T], xor, and, range, len, items, enum, App.UsageOnError

Source · Guide: How to validate input

A scheduler that checks flags against each other in a Validate method. An end date before the start date, or retries with a zero backoff, is a usage error reported before any hook runs.

Date order
$ go run ./_examples/07-dynamic-validation --start-date 2026-03-01 --end-date 2026-01-01
Error:dynamic-validation: error: invalid date range: end-date (2026-01-01) cannot be earlier than start-date (2026-03-01)
Usage:
dynamic-validation [flags]
Run 'dynamic-validation --help' for more information.

Uses: Validator

Source · Guide: How to lint schemas

A struct that also carries validate and db tags for other libraries. Schema build rejects unknown tag keys with ErrSchema, so the program registers those keys with App.AllowTags. They never appear in help or in the value table.

Terminal window
$ go run ./_examples/27-strict-tag-validation --email ops@example.com
FIELD TYPE VALUE SOURCE
--email string ops@example.com ● cli --email
--retries int 3 · default

Uses: App.AllowTags

Source · Guide: How to validate input

A reader that takes its input from exactly one of --input-file or --input-url. Giving neither, or both, is a usage error, and the usage line shows the choice.

One source
$ go run ./_examples/31-oneof-groups --input-file data.txt
source=file:data.txt

Uses: oneof, placeholder

Source · Guide: How to customize help screens

A service tool with help and version commands, -h and -V as the short forms of --help and --version, and custom commands that render help, usage and version themselves. help status shows a multi-line description, examples and a footer.

help status
$ go run ./_examples/10-builtins-help-version help status
Reports the health of every subsystem builtins-help-version manages.
Pass --detailed for per-subsystem diagnostics.
Usage:
builtins-help-version status [flags]
Examples:
builtins-help-version status
builtins-help-version status --detailed
Flags:
-d, --detailed Show detailed subsystem diagnostics
-h, --help Show help
builtins-help-version home: https://example.com/builtins-help-version

Uses: HelpCommand, VersionCommand, App.HelpShortFlag, App.VersionShortFlag, App.Examples, App.HelpFooter, Session.Help, Session.Usage, Session.Version

Source · Guide: How to customize help screens

A help screen that shows both ways to state a constraint. --automatic gets the generated [1..65535] hint. --inlined writes the same bound into its own help text with {{range}}, and the generated hint goes away.

Terminal window
$ go run ./_examples/16-help-variables --help
Help-variable interpolation: state a constraint once
Usage:
help-variables [flags]
Flags:
--automatic=8080 Port using the automatic hint [1..65535]
--inlined=8080 Port stated once (1..65535)
--environment=STRING Environment (dev, staging, prod)
--zones=STRING,... Availability zones (2..3 items)
--profile=STRING Build profile (default dev)
--region=STRING Region (from REGION)
--literal=STRING Literal braces: {{not-a-variable}}
--help Show help
--version Show version

Uses: {{range}}, {{enum}}, {{items}}, {{default}}, {{env}}

Source · Guide: How to deprecate flags and commands

A retired tool that still works but prints a deprecation warning on every run, --help included.

Terminal window
$ go run ./_examples/22-app-deprecation deploy -f
WARNING: app-deprecation is deprecated: use the new unified tool
deployment started

Uses: App.Deprecated

Source · Guide: How to deprecate flags and commands

A CLI where the --old flag and the legacy command still work but warn and name their replacements. Completion stops offering them, so the candidates below include --modern and leave out --old.

Deprecated flag
$ go run ./_examples/23-member-deprecation --old value
WARNING: flag '--old' is deprecated: use --modern instead
old="value" modern=""

Uses: deprecated

Source · Guide: How to bind environment variables

A server CLI that reports where each setting came from: the command line, the environment, a config file, or the default. --why lists each flag’s environment variable and config key.

Environment
$ PORT=9001 go run ./_examples/13-twelve-factor-precedence
FIELD TYPE VALUE SOURCE
-p, --port int 9001 ● env PORT
--host string 127.0.0.1 · default

Uses: ConfigFile, env, config, placeholder, App.EnvPrefix, App.EnableWhy

Source · Guide: How to load .env files

A service that reads .env and .env.local and accepts a config file in JSON, TOML, YAML or HCL. A misspelled config key fails with a suggestion. --why lists the registered decoders and redacts --database-url and --api-key.

Terminal window
$ go run ./_examples/14-multiformat-and-dotenv --why
Value provenance for "multiformat-and-dotenv":
FLAG VALUE SOURCE ENV CONFIG PATH
--config-file unset - -
--service-name api-svc default SERVICE_NAME service-name
--port 8080 default PORT port
--database-url unset DATABASE_URL database-url
--max-workers 4 default MAX_WORKERS max-workers
--api-key unset API_KEY api-key
Config decoders: .hcl, .json, .toml, .yaml, .yml

Uses: App.Dotenv, App.RegisterDecoder, safe

Source · Guide: How to manage config files

A client that merges every config file it finds in /etc, ~/.config and the working directory, with the working directory’s file winning key by key. An explicit --config-file loads that one file instead. --why lists the directories it searched. Paths in the output use /home/alice as the home directory.

Terminal window
$ go run ./_examples/15-cascading-searchpaths --why
Config paths:
. no config file
looked for: config.yaml
looked for: config.yml
looked for: cascading-searchpaths.yaml
looked for: cascading-searchpaths.yml
/home/alice/.config/cascading-searchpaths directory does not exist
looked for: /home/alice/.config/cascading-searchpaths.yaml
looked for: /home/alice/.config/cascading-searchpaths.yml
/etc/cascading-searchpaths directory does not exist
looked for: /etc/cascading-searchpaths.yaml
looked for: /etc/cascading-searchpaths.yml

Uses: App.ConfigOptions, ConfigPaths, ConfigCascading

Source · Guide: How to manage config files

A deploy tool whose -c takes several config files and merges them in order, so a profile file overrides a base file key by key. The two files come from the example’s testdata/profiles.txt. Create them to repeat the run.

deploy/base.yaml
host: base.example.com
port: 9000
log-level: debug

Uses: ConfigFile, multi, ConfigCascading

Source · Guide: How to manage config files

A client that searches three directories for one HCL file and loads the first it finds, with no merging. An explicit -c replaces the whole search. Paths in the output use /home/alice as the home directory.

Terminal window
$ go run ./_examples/18-config-searchpaths --why
Config paths:
. no config file
looked for: config.hcl
looked for: config-searchpaths.hcl
/home/alice/.config/config-searchpaths directory does not exist
looked for: /home/alice/.config/config-searchpaths.hcl
/etc/config-searchpaths directory does not exist
looked for: /etc/config-searchpaths.hcl

Uses: App.ConfigOptions, ConfigPaths

Source · Guide: How to manage config files

A web server that loads bootstrap.yaml unless the user names another file, and stops with exit code 1 when it is missing. The WEB_CONFIG variable replaces it, and --config-file replaces both. The files come from the example’s testdata/explicit.txt. Create them to repeat the runs.

bootstrap.yaml
host: explicit.example.com
port: 9100

Uses: App.ConfigOptions, ConfigExplicit

Source · Guide: How to gate flags and subcommands behind features

An HTTP server with named features declared on the root. --quic exists only while the http3 feature is on, and the admin command only while admin-api is on. Features are switched on from --feature-gates, the API_FEATURES variable, or a features config section.

Gated flag
$ go run ./_examples/29-feature-toggles --quic
Error:feature-toggles: error: flag '--quic' requires feature "http3"
Usage:
feature-toggles [flags]
Run 'feature-toggles --help' for more information.

Uses: Features[T], feature, flag, stage, App.EnableFeatures

Source · Guide: How to load domain documents

A pipeline runner whose -f names a YAML file that has to be read before configuration resolves. Bootstrap reads it, keeps the pipelines for Run, and passes the file’s parallelism, log_level and env keys to the config source.

Terminal window
$ go run ./_examples/30-bootstrapper -f _examples/30-bootstrapper/testdata/fixtures/pipeline.yaml --pipeline deploy
FIELD TYPE VALUE SOURCE
--log-level string debug ● config _examples/30-bootstrapper/testdata/fixtures/pipeline.yaml › pipeline deploy
pipeline deploy: needs=[build] steps=[./deploy.sh]

Uses: Bootstrapper, Bootstrap.SetConfig, ConfigDocument, bootstrap

Source · Guide: How to compute and shape completion candidates

A deploy tool that completes values three ways: types that complete themselves on deploy, named predictors on exec, and the predict package’s constructors and combinators on logs. --list-candidates calls the predictors directly, outside completion. On deploy, enum tags narrow a type’s candidates on --failover and --base-image, and --zones completes map values from the value type.

Completion request
$ go run ./_examples/19-shell-completion __complete export deploy --cluster ''
{"candidates":[{"value":"staging-cluster-alpha","display":"staging-cluster-alpha","tag":"values"},{"value":"staging-cluster-beta","display":"staging-cluster-beta","tag":"values"}],"directives":{"keeporder":false,"messages":[],"noprefix":false,"nospace":false},"usage":"target cluster in staging"}

Uses: Predictable, predict.FileFilterable, predictor, enum, map[K]V, App.Predictor, App.EnableCompletion, CompletionEnvPrefix

Source · Guide: How to use the network, system, and timezone packages

system and network commands whose flags and arguments use the types from CONGA’s system and network packages. The types complete themselves and carry methods such as Signal.Signal() and Port.IsPrivileged().

system kill
$ go run ./_examples/20-modular-predictors system kill -s SIGKILL 42
FIELD TYPE VALUE SOURCE
-s, --signal system.Signal SIGKILL ● cli --signal
<target> system.PID 42 ● cli
Signaling PID 42 with SIGKILL (signal 9)

Uses: system.Signal, system.PID, system.Process, network.Port, network.HTTPStatus, network.MIMEType

Source · Guide: How to enable shell completion

A minifier with no subcommands. Enabling completion adds a --completion <shell> flag, and help still has no Commands section.

Terminal window
$ go run ./_examples/24-flat-completion-flag --help
Asset minifier (flat CLI with default --completion flag)
Usage:
flat-completion-flag [flags] <input>
Arguments:
<input> Input file to minify
Flags:
-l, --level=1 Minification level [1..9]
-o, --output=STRING Output file path
--completion=SHELL Generate shell completion script
--help Show help
--version Show version

Uses: App.EnableCompletion

Source · Guide: How to enable shell completion

A task runner with no other subcommands that declares CompletionCommand, so help lists a completion command in place of the --completion flag.

Terminal window
$ go run ./_examples/25-flat-completion-subcommand --help
Task runner (flat CLI with opt-in completion subcommand)
Usage:
flat-completion-subcommand [flags] <task>
Commands:
completion Generate shell completion script
Arguments:
<task> Task name to execute
Flags:
-d, --dry-run Simulate execution without modifying files
--help Show help
--version Show version

Uses: CompletionCommand, App.EnableCompletion

Source · Guide: How to use lifecycle hooks

A migration tool that prints each hook as it runs, on the root and on the selected command. When Run fails, PostRun is skipped and Finally still runs. When a command’s PreRun fails, its own Run, PostRun and Finally are skipped, and the root’s Finally still runs. Both failures exit with code 1.

Success
$ go run ./_examples/12-lifecycle-hooks migrate -d
[HOOK] 1. Root.PreRun: Initializing global logger & telemetry
[HOOK] 2. MigrateCmd.PreRun: Opening database connection pool
[HOOK] 3. MigrateCmd.Run: Executing migration (dry_run=true)
[HOOK] 3.5. MigrateCmd.PostRun: Committing transaction log
[HOOK] 4. Root.PostRun: Flushing telemetry & metrics
[HOOK] 4.5. MigrateCmd.Finally: Closing database connection pool
[HOOK] 5. Root.Finally: Global teardown completed successfully for "migrate"

Uses: PreRunner, Runner, PostRunner, Finalizer

Source · Guide: How to test a command

A host program that runs a CONGA CLI in-process. It supplies the arguments and streams, calls RunContext, classifies the returned error, and captures the exit code through ExitFunc instead of exiting. Lines starting [host] are the host’s own output.

Success
$ go run ./_examples/26-library-embedding migrate-data --priority 7
Running job migrate-data (priority 7)
stdin payload: "host-provided stdin\n"
[host] captured exit code: 0

Uses: App.Args, App.Stdin, App.Stdout, App.Stderr, App.RunContext, App.ExitFunc, App.DisableHelpFlag, IsUsageError, UsageError, ErrCoerce

Source

One CLI that uses most of CONGA at once: every primitive width, the filesystem types, all four decoders over one schema, map encodings, provenance, features, environment binding, and .env loading. Its configs/ directory holds the same configuration in each format.

Terminal window
$ go run ./_examples/99-kitchen-sink --help
Exhaustive type, configuration-mapping, and value-provenance reference
Usage:
kitchen-sink [<command>] [flags]
Commands:
types Type system matrix (primitives, filesystem, value types)
config Configuration mapping patterns
advanced Required flags, arguments, trailing args, provenance
feature-state Resolved feature state, per-key provenance, and lifecycle hooks
help Show help for any command
version Show version information
completion Generate shell completion scripts
Flags:
-c, --config-file=PATH Path to config file [decoders: .hcl, .json, .toml, .yaml, .yml]
[env: KITCHEN_SINK_CONFIG]
--feature-gates=KEY=VALUE,... Enable or disable features (name=value)
-v, --verbosity [env: KITCHEN_SINK_VERBOSITY]
--format="json" [env: KITCHEN_SINK_FORMAT] [enum: json, yaml, toml, hcl]
--[no-]cache Enable cache [default: true] [env: KITCHEN_SINK_CACHE]
--secret-key=STRING API secret (config key remapped, explicit env name)
[env: KITCHEN_SECRET]
--temp-flag=STRING CLI only (excluded from config files and environment)
--metadata=STRING Arbitrary deployment metadata [env: KITCHEN_SINK_METADATA]
--storm Enable storm mode [env: KITCHEN_SINK_STORM]
--why[=FORMAT] Show resolved field values and where they came from (values
redacted unless tagged safe) [enum: text, json]
--help Show help
--version Show version
Features:
http3 Experimental QUIC/HTTP3 listener [alpha] [env: KITCHEN_SINK_FEATURE_HTTP3]
strict-tls Require TLS and reject weak ciphers [beta] [default: true] [env: KITCHEN_SINK_STRICT]
metrics Expose the metrics endpoint [beta] [default: true]
compression Response compression level (0 = off) [beta] [levels: 1, 2] [default: 1]
[env: KITCHEN_SINK_FEATURE_COMPRESSION]

Uses: ConfigFile, Features[T], RequiredFlag[T], DashArgs, executable, App.AllowTags, App.Dotenv, App.RegisterDecoder

API Examples
aliases 02, 08
and 06
App.AllowTags 27, 99
App.Args 26
App.ConfigOptions 15, 18, 28
App.Deprecated 22
App.DisableHelpFlag 26
App.Dotenv 14, 99
App.EnableCompletion 19, 24, 25
App.EnableFeatures 29
App.EnableWhy 13
App.EnvPrefix 09, 13
App.Examples 10
App.ExitFunc 26
App.HelpFooter 10
App.HelpShortFlag 10
App.Predictor 19
App.RegisterDecoder 14, 99
App.RegisterType 21
App.RunContext 26
App.Stderr 26
App.Stdin 26
App.Stdout 26
App.UsageOnError 06
App.Use 21
App.VersionShortFlag 10
bootstrap 30
Bootstrapper 30
Bootstrap.SetConfig 30
ByteSize 05
Command[T] 08, 32
Command[T].Get 09
CompletionCommand 25
CompletionEnvPrefix 19
config 13
ConfigCascading 15, 17
ConfigDocument 30
ConfigExplicit 28
ConfigFile 13, 17, 99
ConfigPaths 15, 18
Counter 02
DashArgs 11, 99
default 01
{{default}} 16
deprecated 23
Dir 05
enum 06, 19
{{enum}} 16
{{env}} 16
env 13
envprefix 09
ErrCoerce 26
executable 99
existing 05
feature 29
Features[T] 29, 99
File 05
FileContent 05
Finalizer 12
flag 29
glob 05
HelpCommand 10
hidden 02, 08
implicit 32
IsUsageError 26
items 03, 06
{{items}} 16
len 06
map[K]V 03, 19
multi 17
name 04, 32
negatable 03
network.HTTPStatus 20
network.MIMEType 20
network.Port 20
oneof 31
OptionalArg.GetOr 04
OptionalArg[T] 04
OptionalFlag[T] 01
placeholder 13, 31
PostRunner 12
Predictable 19
predict.FileFilterable 19
predictor 19
PreRunner 12
range 06
{{range}} 16
RawArgs 11
RequiredArg[T] 04
RequiredFlag[T] 06, 99
Runner 12
safe 14
section 02, 08
SelfValidator 05
sep 03
Session.Help 10
Session.Name 09
Session.Path 09
Session.Root 09
Session.Usage 10
Session.Version 10
short 01
stage 29
stdin 05
stdout 05
summary 08
symlink 05
system.PID 20
system.Process 20
system.RegisterSignal 21
system.Signal 20
timezone.RegisterLocation 21
UsageError 26
Validator 07
VersionCommand 10
WithPredictor 21
xor 06