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:
$ go run ./_examples/01-minimal-hello --name AliceHello, Alice!Run every example’s tests:
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.
Flags and values
Section titled “Flags and values”01 minimal-hello
Section titled “01 minimal-hello”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.
$ go run ./_examples/01-minimal-helloHello, World!$ go run ./_examples/01-minimal-hello --helpMinimal single-command hello world CLI
Usage: minimal-hello [flags]
Flags: -n, --name="World" Name of the person to greet -l, --loud Print greeting in uppercase --help Show help --version Show versionUses: OptionalFlag[T], default, short
02 flag-primitives
Section titled “02 flag-primitives”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.
$ 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$ go run ./_examples/02-flag-primitives --timeout 5xError:flag-primitives: error: invalid duration "5x" (valid units: ms, s, m, h) for flag --timeoutErrorUses: Counter, aliases, hidden, section
03 negatable-and-maps
Section titled “03 negatable-and-maps”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".
$ 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$ go run ./_examples/03-negatable-and-maps -H 'Accept=text/html,application/json' FIELD TYPE VALUE SOURCE -H, --headers []string [Accept=text/html,application/json] ● cli --headersUses: negatable, map[K]V, items, sep
05 domain-types
Section titled “05 domain-types”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.
$ 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 --headersValidated Domain Types: max_memory_bytes=2147483648$ go run ./_examples/05-domain-types -i missing.txtError:domain-types: error: stat missing.txt: no such file or directory for flag --input-fileError$ go run ./_examples/05-domain-types -i go.mod -p 9000-8000Error:domain-types: error: invalid port range 9000-8000 (must be 1..65535 and min <= max) for flag --portsErrorUses: File, Dir, ByteSize, FileContent, SelfValidator, existing, stdin, stdout, symlink, glob
21 pluggable-types
Section titled “21 pluggable-types”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.
$ 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$ go run ./_examples/21-pluggable-types --load 150%Error:pluggable-types: error: invalid load percentage "150%" (expected 0%-100%) for flag --loadErrorUses: App.Use, timezone.RegisterLocation, system.RegisterSignal, App.RegisterType, WithPredictor
Positional and trailing arguments
Section titled “Positional and trailing arguments”04 positional-args
Section titled “04 positional-args”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.
$ 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] ● cliBroadcast: channel=email message="build failed" urgent=false extra_recipients=2$ go run ./_examples/04-positional-argsError:positional-args: error: missing required positional argument <channel>Error
Usage: positional-args [flags] <channel> [message] [recipients...]
Run 'positional-args --help' for more information.Uses: RequiredArg[T], OptionalArg[T], OptionalArg.GetOr, name
11 trailing-args-forwarding
Section titled “11 trailing-args-forwarding”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 --.
$ 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 ● cliDashArgs container: [-v -run TestAuth]$ go run ./_examples/11-trailing-args-forwarding exec my-container ls -la /var/log FIELD TYPE VALUE SOURCE <container> string my-container ● cli [args...] RawArgs ls -la /var/log ● cliRawArgs container: [ls -la /var/log]Uses: DashArgs, RawArgs
Subcommands
Section titled “Subcommands”08 subcommands-basic
Section titled “08 subcommands-basic”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.
$ go run ./_examples/08-subcommands-basic delteError:subcommands-basic: error: unknown command: delte (did you mean "delete"?)Error$ go run ./_examples/08-subcommands-basic rm web-api -f FIELD TYPE VALUE SOURCE delete (rm, del) command — ▸ selected <name> string web-api ● cli -f, --force bool true ● cli --force$ go run ./_examples/08-subcommands-basic doctor FIELD TYPE VALUE SOURCE doctor command — ▸ selected -f, --fix bool false ○ unsetUses: Command[T], aliases, section, hidden, summary
09 deep-hierarchy-context
Section titled “09 deep-hierarchy-context”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.
$ 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 listActive Leaf Name: listRoot Global Region: us-east-1Ancestor Cluster: default-clusterAncestor Node: node-01Parent Pod Wait: 5sLeaf Status Filter: pending$ FLEET_POD_STATUS=running go run ./_examples/09-deep-hierarchy-context cluster node pod listLeaf Status Filter: runningUses: Session.Root, Command[T].Get, Session.Path, Session.Name, envprefix, App.EnvPrefix
32 implicit-command
Section titled “32 implicit-command”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).
$ go run ./_examples/32-implicit-command ./script.tsrun file=script.ts dry-run=false args=[]$ go run ./_examples/32-implicit-command run ./script.tsrun file=script.ts dry-run=false args=[]$ go run ./_examples/32-implicit-command -n ./script.tsrun file=script.ts dry-run=true args=[]$ go run ./_examples/32-implicit-command --helpCommands: run Execute a file (default) install Install dependenciesUses: Command[T], implicit, name
Validation
Section titled “Validation”06 flag-constraints
Section titled “06 flag-constraints”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.
$ go run ./_examples/06-flag-constraints -k secret --json --yamlError:flag-constraints: error: flags --json and --yaml are mutually exclusiveError
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$ go run ./_examples/06-flag-constraints -k secret --json -u admin --password hunter2 -z a -z bError:flag-constraints: error: value "hunter2" length 7 must be >= 8 for flag --passwordErrorUses: RequiredFlag[T], xor, and, range, len, items, enum, App.UsageOnError
07 dynamic-validation
Section titled “07 dynamic-validation”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.
$ go run ./_examples/07-dynamic-validation --start-date 2026-03-01 --end-date 2026-01-01Error:dynamic-validation: error: invalid date range: end-date (2026-01-01) cannot be earlier than start-date (2026-03-01)Error
Usage: dynamic-validation [flags]
Run 'dynamic-validation --help' for more information.$ go run ./_examples/07-dynamic-validation --max-retries 3 --backoff 0sError:dynamic-validation: error: invalid backoff duration: backoff duration must be positive when max-retries > 0Error
Usage: dynamic-validation [flags]
Run 'dynamic-validation --help' for more information.Uses: Validator
27 strict-tag-validation
Section titled “27 strict-tag-validation”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.
$ 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 · defaultUses: App.AllowTags
31 oneof-groups
Section titled “31 oneof-groups”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.
$ go run ./_examples/31-oneof-groups --input-file data.txtsource=file:data.txt$ go run ./_examples/31-oneof-groupsError:oneof-groups: error: missing required flag: one of --input-file, --input-urlError
Usage: oneof-groups (--input-file=PATH | --input-url=URL)
Run 'oneof-groups --help' for more information.$ go run ./_examples/31-oneof-groups --input-file data.txt --input-url https://example.comError:oneof-groups: error: flags --input-file and --input-url are mutually exclusiveError
Usage: oneof-groups (--input-file=PATH | --input-url=URL)
Run 'oneof-groups --help' for more information.Uses: oneof, placeholder
Help, version, and deprecation
Section titled “Help, version, and deprecation”10 builtins-help-version
Section titled “10 builtins-help-version”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.
$ go run ./_examples/10-builtins-help-version help statusReports 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$ go run ./_examples/10-builtins-help-version version --json{"version":"2.4.1","gitCommit":"","built":"","goVersion":"go1.27.3","os":"linux","arch":"amd64","modified":false}$ go run ./_examples/10-builtins-help-version -Vbuiltins-help-version has version 2.4.1 built with go1.27.3Uses: HelpCommand, VersionCommand, App.HelpShortFlag, App.VersionShortFlag, App.Examples, App.HelpFooter, Session.Help, Session.Usage, Session.Version
16 help-variables
Section titled “16 help-variables”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.
$ go run ./_examples/16-help-variables --helpHelp-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 versionUses: {{range}}, {{enum}}, {{items}}, {{default}}, {{env}}
22 app-deprecation
Section titled “22 app-deprecation”Source · Guide: How to deprecate flags and commands
A retired tool that still works but prints a deprecation warning on every run, --help included.
$ go run ./_examples/22-app-deprecation deploy -fWARNING: app-deprecation is deprecated: use the new unified tooldeployment startedUses: App.Deprecated
23 member-deprecation
Section titled “23 member-deprecation”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.
$ go run ./_examples/23-member-deprecation --old valueWARNING: flag '--old' is deprecated: use --modern insteadold="value" modern=""$ go run ./_examples/23-member-deprecation __complete export --{"candidates":[{"value":"--modern","display":"--modern","style":"blue","tag":"longhand flags"},{"value":"--help","display":"--help","description":"Show help","tag":"longhand flags"},{"value":"--version","display":"--version","description":"Show version","tag":"longhand flags"}],"directives":{"keeporder":false,"messages":[],"noprefix":false,"nospace":false},"usage":""}Uses: deprecated
Configuration and environment
Section titled “Configuration and environment”13 twelve-factor-precedence
Section titled “13 twelve-factor-precedence”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.
$ 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$ go run ./_examples/13-twelve-factor-precedence -p 9003 --whyValue provenance for "twelve-factor-precedence":
FLAG VALUE SOURCE ENV CONFIG PATH --config-file unset SERVER_CONFIG - --port 9003 cli PORT port --host 127.0.0.1 default SERVER_HOST host --environment dev default SERVER_ENVIRONMENT environment --debug false default SERVER_DEBUG debug --worker-id unset SERVER_WORKER_ID worker-id --trace unset - trace --auth-token unset SERVER_AUTH_TOKEN -Uses: ConfigFile, env, config, placeholder, App.EnvPrefix, App.EnableWhy
14 multiformat-and-dotenv
Section titled “14 multiformat-and-dotenv”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.
$ go run ./_examples/14-multiformat-and-dotenv --whyValue 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, .ymlUses: App.Dotenv, App.RegisterDecoder, safe
15 cascading-searchpaths
Section titled “15 cascading-searchpaths”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.
$ go run ./_examples/15-cascading-searchpaths --whyConfig 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.ymlUses: App.ConfigOptions, ConfigPaths, ConfigCascading
17 config-profiles
Section titled “17 config-profiles”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.
host: base.example.comport: 9000log-level: debugport: 9443log-level: warn$ go run ./_examples/17-config-profiles -c deploy/base.yaml -c deploy/prod.yaml FIELD TYPE VALUE SOURCE -c, --config-files conga.ConfigFile deploy/base.yaml, deploy/prod.yaml ● cli --config-file --host string base.example.com ● config deploy/base.yaml -p, --port int 9443 ● config deploy/prod.yaml --log-level string warn ● config deploy/prod.yamlUses: ConfigFile, multi, ConfigCascading
18 config-searchpaths
Section titled “18 config-searchpaths”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.
$ go run ./_examples/18-config-searchpaths --whyConfig 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.hclUses: App.ConfigOptions, ConfigPaths
28 explicit-config-file
Section titled “28 explicit-config-file”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.
host: explicit.example.comport: 9100host: env.example.comport: 9300$ go run ./_examples/28-explicit-config-file FIELD TYPE VALUE SOURCE -c, --config-file conga.ConfigFile bootstrap.yaml ● config bootstrap.yaml --host string explicit.example.com ● config bootstrap.yaml -p, --port int 9100 ● config bootstrap.yaml$ WEB_CONFIG=env.yaml go run ./_examples/28-explicit-config-file FIELD TYPE VALUE SOURCE -c, --config-file conga.ConfigFile env.yaml ● env WEB_CONFIG --host string env.example.com ● config env.yaml -p, --port int 9300 ● config env.yaml$ go run ./_examples/28-explicit-config-fileError:explicit-config-file: error: cannot read config file "bootstrap.yaml": stat bootstrap.yaml: no such file or directoryErrorUses: App.ConfigOptions, ConfigExplicit
29 feature-toggles
Section titled “29 feature-toggles”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.
$ go run ./_examples/29-feature-toggles --quicError:feature-toggles: error: flag '--quic' requires feature "http3"Error
Usage: feature-toggles [flags]
Run 'feature-toggles --help' for more information.$ go run ./_examples/29-feature-toggles --feature-gates http3=true --quiclisten=:8080 cache=128 quic=true insecure=falsefeatures: http3=true admin-api=false strict-tls=true metrics=truemetrics: collecting on :8080$ API_FEATURES=admin-api=true go run ./_examples/29-feature-toggles adminadmin: API listening on :9090Uses: Features[T], feature, flag, stage, App.EnableFeatures
30 bootstrapper
Section titled “30 bootstrapper”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.
$ 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 deploypipeline deploy: needs=[build] steps=[./deploy.sh]Uses: Bootstrapper, Bootstrap.SetConfig, ConfigDocument, bootstrap
Shell completion
Section titled “Shell completion”19 shell-completion
Section titled “19 shell-completion”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.
$ 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"}$ go run ./_examples/19-shell-completion logs api --list-candidatesSeverities: [debug info warn error]Severities matching "w": [warn]KeepOrder directive: trueTag: severitiesUses: Predictable, predict.FileFilterable, predictor, enum, map[K]V, App.Predictor, App.EnableCompletion, CompletionEnvPrefix
20 modular-predictors
Section titled “20 modular-predictors”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().
$ 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 ● cliSignaling PID 42 with SIGKILL (signal 9)$ go run ./_examples/20-modular-predictors network serve -p 80 FIELD TYPE VALUE SOURCE -p, --port network.Port 80 ● cli --portMock responder would listen on port 80 (returning 200 OK, application/json)port privileged: truestatus class: success=true client_error=false server_error=falsemedia: type=application subtype=jsonUses: system.Signal, system.PID, system.Process, network.Port, network.HTTPStatus, network.MIMEType
24 flat-completion-flag
Section titled “24 flat-completion-flag”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.
$ go run ./_examples/24-flat-completion-flag --helpAsset 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 versionUses: App.EnableCompletion
25 flat-completion-subcommand
Section titled “25 flat-completion-subcommand”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.
$ go run ./_examples/25-flat-completion-subcommand --helpTask 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 versionUses: CompletionCommand, App.EnableCompletion
Lifecycle and embedding
Section titled “Lifecycle and embedding”12 lifecycle-hooks
Section titled “12 lifecycle-hooks”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.
$ 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"$ go run ./_examples/12-lifecycle-hooks abort[HOOK] 1. Root.PreRun: Initializing global logger & telemetry[HOOK] 2. AbortCmd.PreRun: Allocating temporary resources[HOOK] 3. AbortCmd.Run: Encountered fatal simulation error![HOOK] 4. AbortCmd.Finally: Rolling back temporary resources (error: simulated fatal transaction failure)[HOOK] 5. Root.Finally: Global teardown executed for "abort" (handling error: simulated fatal transaction failure)Error:lifecycle-hooks: error: simulated fatal transaction failureError$ go run ./_examples/12-lifecycle-hooks deploy[HOOK] 1. Root.PreRun: Initializing global logger & telemetry[HOOK] 2. DeployCmd.PreRun: Pulling container image[HOOK] 5. Root.Finally: Global teardown executed for "deploy" (handling error: unable to reach container registry)Error:lifecycle-hooks: error: unable to reach container registryErrorUses: PreRunner, Runner, PostRunner, Finalizer
26 library-embedding
Section titled “26 library-embedding”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.
$ go run ./_examples/26-library-embedding migrate-data --priority 7Running job migrate-data (priority 7)stdin payload: "host-provided stdin\n"[host] captured exit code: 0$ go run ./_examples/26-library-embedding migrate-data --priority notanumber[host] run error: invalid integer value "notanumber" for flag --priority[host] usage-classified: true[host] usage error at command path: library-embedding[host] coercion failure: invalid integer value "notanumber" for flag --priorityError:library-embedding: error: invalid integer value "notanumber" for flag --priorityError[host] captured exit code: 2Uses: App.Args, App.Stdin, App.Stdout, App.Stderr, App.RunContext, App.ExitFunc, App.DisableHelpFlag, IsUsageError, UsageError, ErrCoerce
Everything together
Section titled “Everything together”99 kitchen-sink
Section titled “99 kitchen-sink”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.
$ go run ./_examples/99-kitchen-sink --helpExhaustive 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
Find an example by API
Section titled “Find an example by API”| 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 |