Documentation
¶
Overview ¶
Package main demonstrates three patterns for reusing and transforming codecs without repeating constraint definitions.
Pattern 1 — Shared field codec variables:
Define portCodec and hostCodec once. Embed them in multiple struct codecs (AppConfig, ProxyConfig). Constraints live in one place; all structs benefit.
Pattern 2 — Sub-codec direct reuse:
dbCodec is defined independently with its own constraints. It is embedded in AppConfig and also passed directly to newDBModule — no re-definition, no constraint duplication.
Pattern 3a — MapCodecSafe (infallible decode):
type Port uint16 wraps portCodec. The port range constraint defined on portCodec runs automatically in the mapped codec's Decode path. Encode is trusted (Refine constraints are decode-only by design).
Pattern 3b — MapCodecValidated (fallible mapping + post-decode validation):
DBConfig is mapped to a DSN string. The to function can fail (malformed host), and cb.Validate enforces DBConfig constraints after the mapping.
Run with: go run ./examples/codec-mapping
Click to show internal directories.
Click to hide internal directories.