Documentation
¶
Overview ¶
Package format bridges Codec[T] to concrete serialization formats (JSON, YAML, TOML).
A codec works with an intermediate representation (map[string]any) that is format-agnostic. Format wraps that intermediate layer so the same codec can read and write multiple wire formats without any changes to the codec itself.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FromEnv ¶ added in v0.3.0
FromEnv loads T from environment variables using schema-driven type coercion.
Naming convention: strings.ToUpper(prefix + field_name). Underscores in field names are preserved:
field "log_level" + prefix "APP_" → "APP_LOG_LEVEL" field "db" + prefix "APP_" → recurse with prefix "APP_DB_" nested field "host" → "APP_DB_HOST"
Supported types (determined from the codec's schema):
flat primitives — direct env var, string coerced by schema type
nested structs — prefix expansion (APP_DB_HOST) OR JSON object (APP_DB='{"host":"..."}')
slices — comma-separated (APP_TAGS=a,b,c) OR JSON array (APP_TAGS='["a","b","c"]')
StringMap — JSON object only (APP_LABELS='{"k":"v"}')
Nullable[T] — absent = nil; present = coerce as inner type
JSON detection: when a field's env var is set and the value starts with '{' or '[' matching the field's schema type, it is parsed as JSON. JSON takes precedence over prefix expansion and comma-split when both would apply (e.g. APP_DB='{...}' takes priority over APP_DB_HOST=...).
Silently skipped: TaggedUnion, slices of objects.
Errors are returned as codex.ValidationErrors. Parse errors (an env var is set but its value cannot be coerced to the field's type) are collected and returned before the codec's Decode runs. Missing required fields and constraint violations are reported by Decode in the same error shape.
Types ¶
type Format ¶
type Format[T any] struct { // contains filtered or unexported fields }
Format binds a Codec[T] to a specific serialization format. Use JSON, YAML, or TOML to construct one.
func New ¶
func New[T any](c codex.Codec[T], marshal func(any) ([]byte, error), unmarshal func([]byte) (any, error)) Format[T]
New creates a Format from a codec and custom marshal/unmarshal functions. Use this to integrate formats not covered by the built-in constructors.
func (Format[T]) Marshal ¶
Marshal encodes v to bytes using the codec and then the format serializer.