Value Encoders
When a session finishes, Ferret encodes the result value into bytes using a codec selected by content type. The Output struct carries the encoded bytes and their MIME type:
Built-in codecs
Two codecs are registered by default:
| Content type | Format | Package |
|---|---|---|
application/json |
JSON (default) | pkg/encoding/json |
application/vnd.msgpack |
MessagePack | pkg/encoding/msgpack |
Selecting the output format
Set the content type when creating a session:
If no content type is set, the session defaults to application/json.
The Codec interface
A codec combines encoding and decoding behind a single content type:
Encoder
Encode converts a runtime value to bytes. EncodeWith returns a configurer for attaching hooks (see below).
Decoder
Decode converts bytes back into a runtime value. DecodeWith returns a configurer for attaching hooks.
Encoder and decoder hooks
Hooks let you intercept encoding and decoding without replacing the codec. The configurer chain builds a new encoder or decoder with hooks attached:
Hook types
| Hook | Signature | When it runs |
|---|---|---|
PreEncoderHook |
func(value runtime.Value) error |
Before encoding a value |
PostEncoderHook |
func(value runtime.Value, err error) error |
After encoding; receives the encode error |
PreDecoderHook |
func(data []byte) error |
Before decoding bytes |
PostDecoderHook |
func(data []byte, err error) error |
After decoding; receives the decode error |
Multiple hooks of the same type run in registration order. If any hook returns an error, processing stops.
The Registry
The encoding.Registry stores codecs by MIME-normalized content type:
Registry methods
| Method | Returns | Purpose |
|---|---|---|
Register(codec) |
error |
Store a codec by its content type |
Codec(contentType) |
Codec, error |
Look up a full codec |
Encoder(contentType) |
Encoder, error |
Look up an encoder |
Decoder(contentType) |
Decoder, error |
Look up a decoder |
Clone() |
*Registry |
Create an independent copy |
Content types are normalized using MIME media type parsing, so application/json and application/json; charset=utf-8 resolve to the same codec.
Registering codecs on the engine
Add or override a single codec:
Replace the entire registry:
When you use WithEncodingRegistry, only the codecs in the provided registry are available. The default JSON and MessagePack codecs are not included unless you add them yourself.
Complete example
A custom codec that encodes values as plain text: