How to add custom flag types
This guide builds a relay command with four flags, each of a type outside CONGA’s built-in parsing: a port range, a route name checked against a pattern, a CIDR network, and a map of named port ranges.
Implement encoding.TextUnmarshaler
Section titled “Implement encoding.TextUnmarshaler”Implement encoding.TextUnmarshaler, one of the interfaces CONGA decodes, with a pointer receiver:
type TextUnmarshaler interface { UnmarshalText(text []byte) error}CONGA decodes every type that implements it, including standard library types such as time.Time and netip.Prefix. Here *PortRange implements it:
type PortRange struct { Start int End int}
func (p *PortRange) UnmarshalText(text []byte) error { var start, end int if n, err := fmt.Sscanf(string(text), "%d-%d", &start, &end); err != nil || n != 2 { return fmt.Errorf("invalid port range %q, expected START-END", text) }
p.Start, p.End = start, end
return nil}
type Relay struct { Ports conga.RequiredFlag[PortRange] `help:"Port range to listen on (START-END)"`}
func (r *Relay) Run(ctx context.Context, session *conga.Session) error { ports := r.Ports.Get() fmt.Fprintf(session.Stdout(), "listening on ports %d-%d\n", ports.Start, ports.End)
return nil}
func main() { app := conga.New[Relay](). Name("relay"). EnvPrefix("RELAY")
if err := app.Run(); err != nil { app.Exit(err) }}$ relay --ports 8000-8100listening on ports 8000-8100The default help placeholder comes from the type name:
$ relay --helpUsage: relay --ports=PORT-RANGE
Flags: --ports=PORT-RANGE Port range to listen on (START-END) [env: RELAY_PORTS] --help Show help --version Show versionA command-line error from UnmarshalText is a usage error (ErrCoerce, exit 2):
$ relay --ports 80Error:relay: error: invalid port range "80", expected START-END for flag --portsErrorDeclare custom field tags with TagSpecProvider
Section titled “Declare custom field tags with TagSpecProvider”Tags let one type serve fields with different rules, each declared next to its field. A route name and a tenant ID can both be of type Slug, each with its own pattern. The built-in conga.File declares existing and glob the same way.
Implement conga.TagSpecProvider to declare the tags:
type TagSpecProvider interface { TagSpecs() []TagSpec}Each conga.TagSpec names a tag and its kind, and can carry a Validate function that CONGA runs on the tag’s value at startup.
Implement conga.ContextAwareTextUnmarshaler to read the tag values:
type ContextAwareTextUnmarshaler interface { UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error}CONGA passes UnmarshalTextWithContext a conga.DecodeContext with the field’s tag values in Tags, and the session’s Stdin and Stdout for a type that reads or writes them.
Here *Slug implements both. TagSpecs declares a pattern tag whose Validate compiles it at startup, and UnmarshalTextWithContext matches each value against it:
type Slug string
func (s *Slug) TagSpecs() []conga.TagSpec { return []conga.TagSpec{{ Name: "pattern", Kind: conga.TagKindString, Validate: func(value string) error { _, err := regexp.Compile(value)
return err }, }}}
func (s *Slug) UnmarshalTextWithContext(text []byte, decodeContext conga.DecodeContext) error { if pattern := decodeContext.Tags.String("pattern"); pattern != "" && !regexp.MustCompile(pattern).Match(text) { return fmt.Errorf("%q does not match %s", text, pattern) }
*s = Slug(text)
return nil}
type Relay struct { Ports conga.RequiredFlag[PortRange] `help:"Port range to listen on (START-END)"` Route conga.RequiredFlag[Slug] `help:"Route name" pattern:"^[a-z][a-z0-9-]*$"`}Validate has already compiled the pattern by the time UnmarshalTextWithContext runs, so regexp.MustCompile can’t panic there. Run now also prints the route:
$ relay --ports 8000-8100 --route checkout-apilistening on ports 8000-8100route checkout-api$ relay --ports 8000-8100 --route Checkout_APIError:relay: error: "Checkout_API" does not match ^[a-z][a-z0-9-]*$ for flag --routeErrorA pattern that doesn’t compile stops the program at startup, before it reads any flag (exit 1). Here the field was given pattern:"^[a-z":
Error:relay: error: struct Relay field Route: schema error: invalid struct tag: tag "pattern": error parsing regexp: missing closing ]: `[a-z`ErrorA misspelled tag stops it the same way:
Error:relay: error: struct Relay field Route: schema error: invalid struct tag: unknown struct tag "patern" (did you mean "pattern"?). Use app.AllowTags("patern") to permit external tagsErrorRegister a parser with RegisterType
Section titled “Register a parser with RegisterType”When a type from another package, such as net.IPNet, implements none of these interfaces, register a conga.TypeParser for it with RegisterType. A TypeParser[U] is a func(raw string) (U, error), so parseCIDR below is a TypeParser[net.IPNet]. conga.WithPredictor attaches completion candidates to every field of that type:
type Relay struct { // ... Allow conga.OptionalFlag[net.IPNet] `help:"Network allowed to connect"`}
func parseCIDR(raw string) (net.IPNet, error) { _, network, err := net.ParseCIDR(raw) if err != nil { return net.IPNet{}, fmt.Errorf("invalid CIDR %q", raw) }
return *network, nil}
func main() { app := conga.New[Relay](). Name("relay"). EnvPrefix("RELAY"). EnableCompletion(). RegisterType(parseCIDR, conga.WithPredictor(predict.Values("10.0.0.0/8", "192.168.0.0/16"))) // ...}Run prints allowing <network> when the flag is set:
$ relay --ports 8000-8100 --route checkout-api --allow 10.1.0.0/16listening on ports 8000-8100route checkout-apiallowing 10.1.0.0/16$ relay --ports 8000-8100 --route checkout-api --allow 10.1.0.0Error:relay: error: invalid CIDR "10.1.0.0" for flag --allowErrorWith the completion script loaded:
$ relay --allow <Tab>Network allowed to connect10.0.0.0/8 192.168.0.0/16Use a custom type in a map flag
Section titled “Use a custom type in a map flag”A map flag decodes each value the way it decodes a single flag value: through a registered TypeParser, the type’s unmarshaler, or built-in parsing. The key’s underlying type must be string. Here the value type is PortRange:
type Relay struct { // ... Expose conga.OptionalFlag[map[string]PortRange] `help:"Named port ranges to expose (NAME=START-END)"`}
func (r *Relay) Run(ctx context.Context, session *conga.Session) error { // ...
expose := r.Expose.Get() for _, name := range slices.Sorted(maps.Keys(expose)) { fmt.Fprintf(session.Stdout(), "exposing %s on %d-%d\n", name, expose[name].Start, expose[name].End) }
return nil}Users repeat the flag:
$ relay --ports 8000-8100 --route checkout-api --expose web=80-90 --expose admin=9000-9010listening on ports 8000-8100route checkout-apiexposing admin on 9000-9010exposing web on 80-90Or separate entries with commas:
$ relay --ports 8000-8100 --route checkout-api --expose web=80-90,admin=9000-9010listening on ports 8000-8100route checkout-apiexposing admin on 9000-9010exposing web on 80-90A bad value names its key:
$ relay --ports 8000-8100 --route checkout-api --expose web=80Error:relay: error: value for key "web": invalid port range "80", expected START-END for flag --exposeErrorWith parseCIDR registered, a map[string]net.IPNet flag decodes its values through it too.
A slice or map type that implements UnmarshalText, such as net.IP, is one value: its unmarshaler decodes the whole flag value.
Know what users see
Section titled “Know what users see”| Mistake | When it shows | Result |
|---|---|---|
| A value the parser or the type’s unmarshaler rejects, from the command line | When the value is bound | Usage error naming the flag, exit 2 |
| The same rejection from the environment or a config file | When the value is bound | ErrConfig, exit 1, naming the flag and source |
A misspelled custom tag, a tag value its Validate rejects, or a custom tag on a field of another type |
Startup, on every run | schema error: invalid struct tag, exit 1 |
| A field of a type with no parser, unmarshaler, or built-in support | Startup, on every run | struct Relay field Allow: schema error: unsupported type net.IPNet; register a parser with app.RegisterType, exit 1 |
A TypeParser for a slice or map type |
RegisterType, on every run |
Panic: conga: RegisterType does not accept map type map[string]main.PortRange; maps bind entry by entry, so register the key or value type instead |
Where to go next
Section titled “Where to go next”- Domain type interfaces: every interface, the decoding order, and the
TagSpecandDecodeContextfields. - How to compute and shape completion candidates: choose where a type’s candidates come from, and read field tags in its completion.
- How to declare flags: the scalar, list, and map flags CONGA parses without a custom type.
- How to read files and standard input: use the built-in
File,Dir,FileContent, andByteSizetypes. - Domain types: the built-in
File,Dir,FileContent, andByteSizetypes.