Documentation
¶
Overview ¶
Package codec provides payload encoding and decoding for event sourcing.
The Codec interface abstracts serialization so that stores, snapshots, and event construction can work with any encoding format. Four implementations are provided:
- CBORCodec: recommended default — canonical CBOR (deterministic, signing-safe)
- JSONCodec: standard encoding/json — universal interop, human-readable
- CBORCompactCodec: stricter CBOR with unknown-field rejection (schema drift guard)
- RawCodec: passthrough for pre-encoded []byte payloads
CBORCodec and CBORCompactCodec are NOT interchangeable: they sort map keys differently (RFC 7049 length-first vs RFC 8949 bytewise-lexical) and the compact codec rejects unknown fields, so data written by one does not round-trip through the other. Choose one codec per store and keep it documented.
Choosing a Codec ¶
Both JSON and CBOR are fully supported across the library. CBOR is recommended for internal serialization: smaller payloads (see BenchmarkTagTradeoffs for measured size reductions across payload shapes), faster to encode and decode, and deterministic (same input always produces the same output bytes — safe for cryptographic signing). JSON is the right choice for external interop, HTTP APIs, debugging, and any case where human-readability matters.
Payloads that will be signed or content-addressed require byte-deterministic encoding. The DeterministicCodec interface makes that a compile-time guarantee: CBORCodec and CBORCompactCodec always satisfy it, JSONCodec satisfies it only in the GOEXPERIMENT=jsonv2 build, and RawCodec never does. Signing modules should accept DeterministicCodec rather than Codec so that a non-deterministic codec choice fails to build instead of silently producing signatures that break on re-encoding.
Usage ¶
codec := codec.JSONCodec{}
data, err := codec.Encode(MyPayload{Name: "Alice"})
var decoded MyPayload
err = codec.Decode(data, &decoded)
Integration ¶
The Codec is used by event.New (auto-marshal payloads), event.DecodePayload[T] (typed decode), and snapshot stores (serialize stream state).
The encryption module provides a composable codec wrapper (encryption.NewCodec) that wraps any Codec with transparent encrypt-on-encode / decrypt-on-decode. It reports its own encoding ("encrypted") and is used with event.WithCodec to create events with encrypted payloads.
Cross-Codec Transcoding ¶
TranscodeToJSON converts a payload from its stamped encoding into JSON bytes — the schema-free bridge for consumers that store events in CBOR but must serve JSON to browsers or REST clients. Non-CBOR payloads pass through unchanged; CBOR is decoded into a generic Go value and re-encoded as JSON.
out, err := codec.TranscodeToJSON(payload, evt.Encoding())
It is schema-free: CBOR maps become JSON objects, but structs encoded with the cbor:",toarray" tag become JSON arrays (field names are lost). For schema-aware JSON, decode with the concrete type first, then json.Marshal. The transport/http package provides CBORToJSONTransform, a ready-made adapter that wraps TranscodeToJSON for use with WithPayloadTransform.
TranscodeToJSON is a one-way operation: CBOR → JSON. There is intentionally no TranscodeToCBOR because the reverse direction cannot reconstruct CBOR type information (map key order, toarray positions, keyasint integers) from JSON without the original Go type. To produce CBOR, decode into the concrete type and encode with CBORCodec directly.
CBOR Compact Encoding (toarray) ¶
For maximum payload size reduction (~30-40%), add the cbor:",toarray" struct tag to event payload types. This encodes structs as positional CBOR arrays instead of keyed maps, eliminating field-name string overhead entirely.
type UserCreated struct {
_ struct{} `cbor:",toarray"`
Name string
Email string
Time int64
}
Without toarray (map encoding): {"Name":"Alice","Email":"[email protected]","Time":1700000000} With toarray (array encoding): ["Alice","[email protected]",1700000000]
The toarray tag works with both CBORCodec and CBORCompactCodec. It is a per-type decision — mix array-encoded and map-encoded types freely. Once a struct uses toarray, field ORDER is part of the wire format and cannot be reordered without breaking existing data. Add new fields only at the end.
For additional compactness, use CBORCompactCodec (CoreDetEncOptions + ExtraReturnErrors for schema drift detection). See CBORCompactCodec docs.
Zero-Allocation Encoding ¶
Codecs that implement the BufferEncoder interface can write directly into a caller-provided bytes.Buffer, avoiding the allocation returned by Encode. This is useful in hot paths where buffer reuse eliminates GC pressure.
buf := &bytes.Buffer{}
if be, ok := codec.(codec.BufferEncoder); ok {
_ = be.EncodeToBuffer(payload, buf)
}
For even simpler pool-backed encoding, use EncodePooled, which manages a sync.Pool-backed buffer automatically via a callback:
err := codec.EncodePooled(cborCodec, event, func(data []byte) error {
_, werr := store.Write(data)
return werr
})
Streaming ¶
For large event batches, streaming encoders/decoders avoid materializing the full byte slice in memory. Both CBOR and JSON are supported:
enc := codec.NewCBOREncoder(w) // or codec.NewJSONEncoder(w)
_ = enc.Encode(event1)
_ = enc.Encode(event2)
dec := codec.NewCBORDecoder(r) // or codec.NewJSONDecoder(r)
for {
var evt Event
if err := dec.Decode(&evt); err != nil { break }
events = append(events, evt)
}
JSON streaming uses newline-delimited JSON (NDJSON / JSON Lines): each Encode call writes one JSON value followed by a newline, and Decode reads one value at a time, skipping whitespace between values.
Observability ¶
ObserveCodec wraps any Codec with opt-in telemetry: per-operation call counts, byte totals, error counts, and last errors (CodecMetrics), plus a push-style MetricsHook for Prometheus/OpenTelemetry-style exporters. The wrapper is goroutine-safe and preserves the BufferEncoder fast path when present.
obs := codec.ObserveCodec(codec.CBORCodec{},
codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, n int, err error) {
// emit to your metrics backend
}),
)
Errors ¶
Every error returned by this package carries a stable machine-readable code and a behavioral family (github.com/larsartmann/go-error-family): Rejection for caller input faults, Corruption for undecodable stored or wire bytes, Infrastructure for system-level failures, and Orchestration for internal invariant violations. Sentinel identities (ErrUnknownEncoding, ErrEncodeRawType, ErrInvalidCOSESign1, …) match via errors.Is even when wrapped, and factual details (the offending encoding, the failing COSE part) live in the error's structured context:
_, err := codec.ForEncoding(enc)
if e, ok := errors.AsType[*errorfamily.Error](err); ok {
log.Printf("code=%s family=%v encoding=%s",
e.Code(), e.ErrorFamily(), e.ErrorContext()["encoding"])
}
The full code table lives in docs/error-codes.md (registry, tripwired in CI by scripts/check-error-codes.sh); the design rationale, including the WrapOnce rule and the classified-vs-passthrough split, is in docs/adr/0001-error-taxonomy.md.
Format Detection ¶
AutoDetect infers the encoding (json/cbor/raw) of unknown payload bytes from the leading byte, with trial-decode fallback for ambiguous starts. It is a best-effort heuristic for diagnostics and tooling, NOT a security boundary. AutoDetectDebug additionally returns a stable DetectionReason to branch on and a human-readable Detail string for logs (unstable wording — never parse).
Performance ¶
fxamacker/cbor caches type metadata in a process-wide sync.Map keyed by reflect.Type. The first encode/decode of each type pays a one-time reflection cost (~100µs); subsequent operations reuse the cached metadata (~300ns for a 7-field struct). Code generation is NOT needed for typical use cases — the cache handles it. Use EncodePooled or BufferEncoder to eliminate allocation overhead on hot paths.
The toarray and keyasint struct tags reduce payload size by eliminating field-name strings. Measured tradeoffs across payload shapes:
Payload map (bytes) toarray (bytes) keyasint (bytes) small (3) 56 43 (-23%) 46 (-18%) medium (7) 218 156 (-28%) 168 (-23%) large (12) 270 159 (-41%) 171 (-37%)
toarray produces the smallest payloads but encodes field order as positional (reordering fields breaks stored data). keyasint is slightly larger but preserves field identity via stable integer keys (safer for schema evolution). Run BenchmarkTagTradeoffs_Encode / BenchmarkTagTradeoffs_Decode for details.
CBOR Compact Struct Tags ¶
fxamacker/cbor supports two struct tags for further payload optimization:
keyasint — encode struct fields as integer keys instead of string keys. This eliminates field-name strings entirely, ideal for high-frequency events with many fields.
type OrderPlaced struct {
_ struct{} `cbor:",keyasint"`
UserID uint64 `cbor:"1,keyasint"`
ItemID uint64 `cbor:"2,keyasint"`
Qty int `cbor:"3,keyasint"`
}
omitzero — omit fields that are zero-valued. Reduces payload size for events where many fields are optional.
type UserUpdated struct {
Name string `cbor:"name"`
Email string `cbor:"email,omitempty"`
Bio string `cbor:"bio,omitzero"`
}
Both tags work with CBORCodec and CBORCompactCodec. Once adopted, the integer key mapping is part of the wire format — changing key numbers breaks existing data.
Index ¶
- Constants
- Variables
- func AssignBase64JSON(data []byte, module, noun string, target *[]byte) error
- func CBORDecMode() cbor.DecMode
- func CBOREncMode() cbor.EncMode
- func COSEAlgHeader(alg int64) ([]byte, error)
- func COSEEncrypt0Diagnostic(data []byte) string
- func COSESign1Diagnostic(data []byte) string
- func DecodeBase64String(encoded string) ([]byte, error)
- func DecodeEnvelopeOrLegacy[T any](data []byte, configured Codec) (T, error)
- func Diagnose(data []byte) (string, error)
- func EncStructure0(bodyProtected, externalAAD []byte) ([]byte, error)
- func EncodePooled(enc BufferEncoder, v any, fn func([]byte) error) error
- func GetBuffer() *bytes.Buffer
- func MarshalBase64JSON(raw []byte) ([]byte, error)
- func MarshalBase64JSONWithModule(raw []byte, module, noun string) ([]byte, error)
- func MarshalCOSEEncrypt0(msg COSEEncrypt0) ([]byte, error)
- func MarshalCOSEProtectedHeader(headers map[int64]any) ([]byte, error)
- func MarshalCOSESign1(msg COSESign1) ([]byte, error)
- func NewCBORDecoder(r io.Reader) *cbor.Decoder
- func NewCBOREncoder(w io.Writer) *cbor.Encoder
- func NormalizeCOSEAlgorithm(v any) (int64, error)
- func PrepareCOSESetup[Cfg any, O ~func(*Cfg)](cfg *Cfg, opts []O, alg int64) ([]byte, error)
- func PutBuffer(b *bytes.Buffer)
- func SigStructure(bodyProtected, externalAAD, payload []byte) ([]byte, error)
- func TranscodeToJSON(payload []byte, enc Encoding) ([]byte, error)
- func UnmarshalBase64JSON(data []byte, module, noun string) ([]byte, error)
- func UnmarshalCOSEProtectedHeader(data []byte) (map[int64]any, error)
- func WrapCOSEMarshal(data []byte, err error, module, noun string) ([]byte, error)
- func WrapEncode(v any, c Codec) ([]byte, error)
- type AutoDetectResult
- type BufferEncoder
- type CBORCodec
- type CBORCompactCodec
- type COSEEncrypt0
- type COSESign1
- type Codec
- type CodecMetrics
- type DetectionReason
- type DeterministicCodec
- type Encoding
- type JSONCodec
- type JSONDecoder
- type JSONEncoder
- type MetricsHook
- type MetricsSnapshot
- type ObservableCodec
- type ObserveOption
- type Operation
- type RawCodec
- type SizeResult
Examples ¶
- AutoDetect
- AutoDetectDebug
- BufferEncoder
- CBORCodec
- CBORCodec (Keyasint)
- CBORCodec (Time)
- CBORCodec (Toarray)
- CBORCompactCodec
- CBOREncMode
- DeterministicCodec
- Diagnose
- EncodePooled
- ForEncoding (Classified)
- JSONCodec
- MetricsHook
- MetricsSnapshot
- NewCBOREncoder
- NewJSONEncoder
- ObserveCodec
- RawCodec
- Size
- TranscodeToJSON
Constants ¶
const ( COSEHeaderAlg int64 = 1 COSEHeaderCrit int64 = 2 COSEHeaderContentType int64 = 3 COSEHeaderKid int64 = 4 COSEHeaderIV int64 = 5 COSEHeaderPartialIV int64 = 6 )
COSE header parameter labels from the IANA "COSE Header Parameters" registry. See https://www.iana.org/assignments/cose/cose.xhtml
const ( COSEAlgHMACSHA256_64 int64 = 4 COSEAlgHMACSHA256 int64 = 5 COSEAlgAES256GCM int64 = 3 COSEAlgChaCha20Poly1305 int64 = 24 COSEAlgEdDSA int64 = -8 COSEAlgEd25519 int64 = -19 )
COSE algorithm identifiers from the IANA "COSE Algorithms" registry. These are the algorithms used by the signing and encryption modules.
Variables ¶
var ( ErrEncodeRawType error = errorfamily.NewRejection( "codec.raw_encode_type", "raw codec: expected []byte", ) ErrDecodeRawType error = errorfamily.NewRejection( "codec.raw_decode_type", "raw codec: expected *[]byte target", ) ErrInvalidCOSESign1 error = errorfamily.NewRejection( "codec.invalid_cose_sign1", "COSE_Sign1 structure has an invalid number of elements", ) ErrInvalidCOSEEncrypt0 error = errorfamily.NewRejection( "codec.invalid_cose_encrypt0", "COSE_Encrypt0 structure has an invalid number of elements", ) ErrCOSEAlgorithmOverflow error = errorfamily.NewRejection( "codec.cose_algorithm_overflow", "COSE algorithm value overflows int64", ) ErrCOSEInvalidAlgorithm error = errorfamily.NewRejection( "codec.cose_invalid_algorithm", "COSE algorithm value is not an integer", ) ErrNormalizeDepthExceeded error = errorfamily.NewRejection( "codec.normalize_depth_exceeded", "codec: normalizeForJSON recursion depth exceeded", ) )
Stable sentinel identities for the codec package. Declared as the `error` interface so errors.Is call sites match the sentinel guard; in-package wraps use errorfamily.Wrapf with the SAME code, so wrapped errors still match via code+family identity.
var ErrUnknownEncoding error = errorfamily.NewRejection(
"codec.unknown_encoding",
"codec: unknown encoding (no built-in codec)",
)
ErrUnknownEncoding is returned by ForEncoding when no built-in codec matches the requested encoding. Declared as the `error` interface so errors.Is call sites match the sentinel guard.
Functions ¶
func AssignBase64JSON ¶
AssignBase64JSON unmarshals data and assigns the decoded bytes to *target. Convenience for types whose underlying type is []byte (encryption.Ciphertext, signing.Signature, etc.) — collapses the standard UnmarshalJSON body to one call so each []byte wrapper type does not repeat the decode+assign boilerplate.
func CBORDecMode ¶
CBORDecMode returns the CBOR decoding mode with duplicate map key enforcement. External packages (e.g. storage/pebble) should use this instead of creating their own identical DecMode.
func CBOREncMode ¶
CBOREncMode returns the canonical CBOR encoding mode (RFC 7049 sorted map keys). Used by storage/pebble and other modules that need deterministic CBOR encoding identical to what CBORCodec produces.
Example ¶
ExampleCBOREncMode demonstrates using the exported canonical encoding mode directly. Storage backends should use this instead of creating their own CBOR mode, ensuring all modules share one deterministic encoding.
package main
import (
"fmt"
"log"
"github.com/larsartmann/go-codec"
)
func main() {
type Snapshot struct {
State string
N int
}
snap := Snapshot{State: "active", N: 42}
// Same canonical EncMode used by CBORCodec internally
data, err := codec.CBOREncMode().Marshal(snap)
if err != nil {
log.Fatal(err)
}
var decoded Snapshot
_ = codec.CBORDecMode().Unmarshal(data, &decoded)
fmt.Printf("%s/%d (%d bytes)\n", decoded.State, decoded.N, len(data))
}
Output: active/42 (18 bytes)
func COSEAlgHeader ¶
COSEAlgHeader returns the CBOR-encoded protected header for a COSE message that carries only the algorithm identifier (alg). This is the common case for COSE_Encrypt0 and COSE_Sign1 messages where the protected header contains no additional parameters.
The returned error is already wrapped as an Infrastructure error so callers (encryption, signing) don't need per-module error wrapping.
func COSEEncrypt0Diagnostic ¶
COSEEncrypt0Diagnostic returns a human-readable diagnostic notation of a COSE_Encrypt0 message for debugging.
func COSESign1Diagnostic ¶
COSESign1Diagnostic returns a human-readable diagnostic notation of a COSE_Sign1 message for debugging. It panics only if CBOR diagnosis itself fails, which cannot happen for valid CBOR data.
func DecodeBase64String ¶
DecodeBase64String decodes a base64-encoded string, trying URL-safe encoding first, then falling back to standard base64 for backward compatibility with legacy consumers.
func DecodeEnvelopeOrLegacy ¶ added in v0.2.0
DecodeEnvelopeOrLegacy decodes data that may be envelope-wrapped or raw (pre-envelope) into T, keeping the permanent-readability guarantee of UnwrapDecode while honoring the caller's configured codec:
- Envelope-wrapped data decodes via its stamped codec (first attempt).
- Raw data decodes via the configured codec first.
- If that fails and the codec is one of the two standard codecs, exactly one cross-retry with the other (JSON↔CBOR) rescues legacy rows written by a differently-configured store.
- Custom codecs get the configured-codec attempt only — their data only decodes with themselves.
Truly undecodable data returns the primary decode error unwrapped, so callers can classify it (e.g. as Corruption) with their own context.
func Diagnose ¶
Diagnose converts CBOR bytes to extended diagnostic notation (EDN) — a human-readable representation of CBOR data. Useful for debugging corrupt events or inspecting raw CBOR payloads without decoding into a Go struct.
cborData, _ := codec.CBORCodec{}.Encode(event)
diag, _ := codec.Diagnose(cborData)
log.Printf("CBOR event: %s", diag)
Example ¶
ExampleDiagnose converts CBOR bytes to human-readable diagnostic notation. Useful for debugging corrupt events or inspecting raw CBOR payloads.
c := codec.CBORCodec{}
type User struct {
Name string
Email string
}
data, _ := c.Encode(User{Name: testName, Email: testEmail})
diag, _ := codec.Diagnose(data)
// Diagnostic notation is a map-like representation
fmt.Println(strings.Contains(diag, testName))
Output: true
func EncStructure0 ¶
EncStructure0 builds the Enc_structure used for COSE_Encrypt0 encryption and decryption as defined in RFC 9052 Section 5.3.
func EncodePooled ¶ added in v0.2.0
func EncodePooled(enc BufferEncoder, v any, fn func([]byte) error) error
EncodePooled encodes v using a pooled *bytes.Buffer and passes the encoded bytes to fn. The buffer is returned to the pool after fn returns, so fn must not retain references to the byte slice after returning — if it needs to keep the bytes, it must copy them.
This eliminates the per-call []byte allocation of Codec.Encode in hot paths where the caller processes the encoded bytes immediately (e.g., writing to a store, sending over the wire). For callers that need to keep the bytes, use Codec.Encode instead.
cbor := codec.CBORCodec{}
err := codec.EncodePooled(cbor, event, func(data []byte) error {
_, werr := store.Write(data)
return werr
})
Example ¶
ExampleEncodePooled demonstrates zero-allocation encoding using a pooled buffer. The callback receives the encoded bytes and must copy them if it needs to retain them after the callback returns — the buffer is returned to the pool immediately.
type Event struct {
Type string
Data string
}
c := codec.CBORCodec{}
evt := Event{Type: testEventCreated, Data: "hello"}
var encoded []byte
err := codec.EncodePooled(c, evt, func(data []byte) error {
encoded = append([]byte(nil), data...) // copy: data is invalid after callback
return nil
})
if err != nil {
fmt.Println("error:", err)
return
}
var decoded Event
_ = c.Decode(encoded, &decoded)
fmt.Println(decoded.Type, decoded.Data)
Output: created hello
func GetBuffer ¶ added in v0.2.0
GetBuffer returns a zeroed *bytes.Buffer from the pool. The caller owns the buffer until PutBuffer is called.
func MarshalBase64JSON ¶
MarshalBase64JSON encodes raw bytes as a URL-safe base64 JSON string. Used by types that wrap []byte and need deterministic JSON marshalling (encryption.Ciphertext, signing.Signature, event.EventID, etc.).
func MarshalBase64JSONWithModule ¶
MarshalBase64JSONWithModule encodes raw bytes as base64 JSON and wraps any error with the given module and noun (e.g. "encryption", "ciphertext" → "encryption.marshal_ciphertext"). Symmetric with AssignBase64JSON — collapses the standard MarshalJSON body to one call.
func MarshalCOSEEncrypt0 ¶
func MarshalCOSEEncrypt0(msg COSEEncrypt0) ([]byte, error)
MarshalCOSEEncrypt0 encodes a COSE_Encrypt0 structure to CBOR bytes.
func MarshalCOSEProtectedHeader ¶
MarshalCOSEProtectedHeader serializes a COSE protected header map to the CBOR bytes that are wrapped in a byte string inside the COSE message. The encoding uses the canonical CBOR mode shared with CBORCodec.
func MarshalCOSESign1 ¶
MarshalCOSESign1 encodes a COSE_Sign1 structure to CBOR bytes.
func NewCBORDecoder ¶
NewCBORDecoder creates a streaming CBOR decoder that reads from r. Use for decoding large event batches from a stream without loading all bytes into memory at once. The decoder uses the same decoding mode as CBORCodec.
func NewCBOREncoder ¶
NewCBOREncoder creates a streaming CBOR encoder that writes to w. Use for encoding large event batches without materializing the full byte slice in memory. The encoder uses the same canonical encoding mode as CBORCodec.
Example ¶
ExampleNewCBOREncoder demonstrates streaming CBOR encoding for large event batches without materializing the full byte slice in memory.
type Event struct {
Type string
Data string
}
var buf bytes.Buffer
enc := codec.NewCBOREncoder(&buf)
_ = enc.Encode(Event{Type: testEventType, Data: testUserName})
_ = enc.Encode(Event{Type: testEventType, Data: "bob"})
// Decode the stream
dec := codec.NewCBORDecoder(&buf)
var events []Event
for {
var evt Event
if err := dec.Decode(&evt); err != nil {
break
}
events = append(events, evt)
}
fmt.Printf("%d events decoded from stream\n", len(events))
Output: 2 events decoded from stream
func NormalizeCOSEAlgorithm ¶
NormalizeCOSEAlgorithm converts a CBOR-decoded algorithm value to int64. CBOR decodes integers as the narrowest Go type that fits, which means small positive values arrive as uint64. This helper normalizes all integer variants to int64 so callers can compare against the COSEAlg* constants. Returns ErrCOSEAlgorithmOverflow for values that exceed int64, and ErrCOSEInvalidAlgorithm for non-integer types.
func PrepareCOSESetup ¶
PrepareCOSESetup applies COSE options to cfg and returns the protected header for the given algorithm. Shared by encryption.EncryptCOSE0 and signing.SignCOSE1 to eliminate the duplicated apply-opts + alg-extraction + header-build boilerplate that art-dupl flagged across those modules.
The caller passes a pointer to its module-local config (e.g. coseEncryptConfig or coseSignConfig); the options are applied in place. The O type parameter has a ~func(*Cfg) constraint so module-local defined option types (COSEEncryptOption, COSESignOption) satisfy it directly.
func PutBuffer ¶ added in v0.2.0
PutBuffer returns a buffer to the pool for reuse. Do not use the buffer after calling PutBuffer. Buffers larger than 1 MiB are discarded to avoid memory bloat from oversized payloads.
func SigStructure ¶
SigStructure builds the Sig_structure used for COSE_Sign1 signing and verification as defined in RFC 9052 Section 4.4.
func TranscodeToJSON ¶
TranscodeToJSON converts a payload from its stamped encoding into JSON bytes. It is the generic, schema-free bridge for consumers that must serve JSON to clients (browsers, REST APIs) while storing events in a compact encoding (CBOR). This deletes the per-consumer CBOR→JSON transcode logic that every compact-codec deployment otherwise duplicates.
Behaviour by encoding:
- EncodingJSON: payload returned unchanged (already JSON).
- EncodingRaw: payload returned unchanged (caller asserts it is valid JSON).
- EncodingCBOR: payload is decoded into a generic Go value (map/slice/scalar) and re-encoded as JSON, preserving the CBOR data model.
TranscodeToJSON is schema-free: it does NOT know the original Go struct type. CBOR maps become JSON objects; CBOR arrays — including structs encoded with the cbor:",toarray" tag — become JSON arrays. For schema-aware decoding (field names, typed values), use event.DecodePayloadAuto[T] with the concrete type.
Map key order is NOT deterministic: the generic decode produces a map[string]any, and json.Marshal iterates Go maps in non-deterministic order. This is correct for browser SSE (JSON objects are unordered) but unsuitable for byte-deterministic use cases (content hashing, cache keys, byte-for-byte comparisons). Callers needing stable key order must use event.DecodePayloadAuto[T] with a concrete struct type, which produces field-order (declaration-order) JSON output.
An error is returned only when CBOR decoding or JSON encoding fails. Callers that want graceful degradation (fall back to the raw payload on failure) should ignore the error and use the original bytes — see transport/http.CBORToJSONTransform for a ready-made [WithPayloadTransform] adapter that does exactly this.
Example ¶
ExampleTranscodeToJSON converts a stored CBOR payload into JSON bytes for serving to browsers or REST clients without knowing the original Go type.
c := codec.CBORCodec{}
type User struct {
Name string
}
cborBytes, err := c.Encode(User{Name: testName})
if err != nil {
fmt.Println("error:", err)
return
}
jsonBytes, err := codec.TranscodeToJSON(cborBytes, codec.EncodingCBOR)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(jsonBytes))
Output: {"Name":"Alice"}
func UnmarshalBase64JSON ¶
UnmarshalBase64JSON unmarshals a JSON string field and decodes it from URL-safe (or standard) base64. The module and noun parameters produce meaningful error locations: e.g. module="signing", noun="signature" yields "signing.unmarshal_signature" and "signing.decode_signature".
func UnmarshalCOSEProtectedHeader ¶
UnmarshalCOSEProtectedHeader deserializes a COSE protected header map from its CBOR-encoded form.
func WrapCOSEMarshal ¶
WrapCOSEMarshal wraps a COSE marshal result with infrastructure error handling. Used by encryption (COSE_Encrypt0) and signing (COSE_Sign1) to centralise the if-err-wrap pattern with a consistent error code format ("<module>.cose_marshal") and message ("marshal <noun>").
func WrapEncode ¶
WrapEncode serializes v with codec c and wraps the result in a JSON envelope. The envelope itself is always JSON-encoded so it can be read without knowing the inner codec. Callers should use UnwrapDecode on the read path to extract the codec and inner data, or fall back to raw decode for old data.
Types ¶
type AutoDetectResult ¶ added in v0.2.0
type AutoDetectResult struct {
Encoding Encoding
Reason DetectionReason
Detail string
}
AutoDetectResult carries the encoding chosen by AutoDetect plus the reason.
Reason is the STABLE, machine-readable contract: branch on it in code. Detail is human-readable, intended for logs and triage output only. Its exact wording and format are NOT part of the API contract and may change in any release — never parse it.
func AutoDetectDebug ¶ added in v0.2.0
func AutoDetectDebug(data []byte) AutoDetectResult
AutoDetectDebug is the verbose form of AutoDetect: it returns not only the inferred encoding but also the reason and a human-readable detail string. Use it when triaging mixed-encoding streams or when logging the decision path. Branch on Reason (stable); treat Detail as diagnostic prose (unstable).
Example ¶
ExampleAutoDetectDebug demonstrates explainable format detection: beyond the inferred encoding, it returns a stable DetectionReason to branch on and a human-readable Detail for logs. Detail is NOT a stable contract — never parse it.
package main
import (
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
for _, data := range [][]byte{
[]byte(`{"name":"Alice"}`),
{0xa1, 0x64, 'n', 'a', 'm', 'e', 0x65, 'A', 'l', 'i', 'c', 'e'}, // CBOR map
{0x1f}, // unrecognized
} {
result := codec.AutoDetectDebug(data)
switch result.Reason {
case codec.DetectionReasonJSONStructure, codec.DetectionReasonJSONTrialDecode:
fmt.Println("json")
case codec.DetectionReasonCBORMajorType, codec.DetectionReasonCBORTrialDecode:
fmt.Println("cbor")
case codec.DetectionReasonEmpty,
codec.DetectionReasonOversized,
codec.DetectionReasonUnknown:
fmt.Printf("other (%s): %s\n", result.Reason, result.Detail)
}
}
}
Output: json cbor other (unknown): first byte 0x1f does not match any known format
type BufferEncoder ¶
BufferEncoder is an optional interface that Codecs can implement for zero-allocation encoding. Instead of allocating a new []byte on every Encode call, EncodeToBuffer writes directly into a caller-provided buffer. Callers can reuse the buffer across calls to eliminate GC pressure in hot paths (batch event publishing, bulk snapshot saving).
Example ¶
ExampleBufferEncoder demonstrates zero-allocation encoding by writing directly into a caller-provided buffer. Useful in hot paths where buffer reuse eliminates GC pressure.
package main
import (
"bytes"
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
type Metric struct {
Name string
Value float64
}
c := codec.CBORCodec{}
buf := &bytes.Buffer{}
// Reuse the same buffer across multiple encode calls
for _, m := range []Metric{
{Name: "cpu", Value: 0.42},
{Name: "mem", Value: 0.87},
} {
buf.Reset()
if be, ok := any(c).(codec.BufferEncoder); ok {
_ = be.EncodeToBuffer(m, buf)
}
fmt.Printf("%d bytes ", buf.Len())
}
fmt.Println("done")
}
Output: 25 bytes 25 bytes done
type CBORCodec ¶
type CBORCodec struct{}
CBORCodec implements Codec using fxamacker/cbor with canonical encoding (RFC 7049: sorted map keys, shortest floats). Canonical mode is deterministic, making CBORCodec safe for content-addressed storage and cryptographic signing.
Encoding mode: CanonicalEncOptions (RFC 7049 §3.9 "Canonical CBOR"). Evaluated CoreDetEncOptions (RFC 7049bis "Core Deterministic") — not adopted because it uses SortBytewiseLexical vs SortLengthFirst, changing all output bytes and breaking existing stored CBOR data + signatures.
Example ¶
c := codec.CBORCodec{}
type User struct {
Name string
}
data, err := c.Encode(User{Name: testName})
if err != nil {
fmt.Println("error:", err)
return
}
var user User
err = c.Decode(data, &user)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(user.Name)
Output: Alice
Example (Keyasint) ¶
ExampleCBORCodec_keyasint demonstrates the keyasint struct tag that encodes field names as compact integer keys instead of strings. This is the COSE/CWT (CBOR Web Token) pattern used by JWT-like claims: each field gets a small integer key, shrinking payloads without losing the self-describing map structure (unlike toarray, field order doesn't matter).
package main
import (
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
c := codec.CBORCodec{}
// Integer keys follow the CWT claim registry (RFC 8392).
type Claims struct {
Iss string `cbor:"1,keyasint"`
Sub string `cbor:"2,keyasint"`
Aud string `cbor:"3,keyasint"`
Exp int64 `cbor:"4,keyasint"`
}
// String-keyed equivalent for size comparison
type ClaimsString struct {
Iss string
Sub string
Aud string
Exp int64
}
claims := Claims{Iss: "s6BhdRkqt3", Sub: "24400320", Aud: "s6BhdRkqt3", Exp: 1735689600}
data, _ := c.Encode(claims)
stringData, _ := c.Encode(ClaimsString(claims))
fmt.Printf("keyasint: %d bytes, string keys: %d bytes\n", len(data), len(stringData))
var decoded Claims
_ = c.Decode(data, &decoded)
fmt.Println(decoded.Iss)
}
Output: keyasint: 41 bytes, string keys: 53 bytes s6BhdRkqt3
Example (Time) ¶
ExampleCBORCodec_time shows time.Time round-tripping through CBOR. Times are encoded as epoch values (TimeUnixDynamic), so the instant survives but the original time zone does not: normalize with .UTC() before encoding and re-normalize after decoding.
package main
import (
"fmt"
"time"
"github.com/larsartmann/go-codec"
)
func main() {
c := codec.CBORCodec{}
created := time.Date(2026, 8, 14, 12, 0, 0, 0, time.UTC)
data, err := c.Encode(created)
if err != nil {
fmt.Println("error:", err)
return
}
var decoded time.Time
if err := c.Decode(data, &decoded); err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(decoded.UTC())
}
Output: 2026-08-14 12:00:00 +0000 UTC
Example (Toarray) ¶
ExampleCBORCodec_toarray demonstrates the toarray struct tag that encodes structs as positional CBOR arrays instead of keyed maps, reducing payload size by 30-40% by eliminating field-name string overhead.
package main
import (
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
c := codec.CBORCodec{}
// The _ field with `cbor:",toarray"` tag enables positional encoding.
// Field ORDER becomes part of the wire format — add new fields only at end.
type PaymentProcessed struct {
_ struct{} `cbor:",toarray"`
PaymentID string
AmountCents int64
Currency string
OccurredAt int64
}
payload := PaymentProcessed{
PaymentID: "pay_abc123",
AmountCents: 4999,
Currency: "USD",
OccurredAt: 1700000000,
}
mapCodec := codec.JSONCodec{}
mapData, _ := mapCodec.Encode(payload)
arrayData, _ := c.Encode(payload)
fmt.Printf("JSON: %d bytes, CBOR+toarray: %d bytes (%.0f%% smaller)\n",
len(mapData), len(arrayData),
float64(len(mapData)-len(arrayData))/float64(len(mapData))*100)
var decoded PaymentProcessed
_ = c.Decode(arrayData, &decoded)
fmt.Println(decoded.PaymentID, decoded.AmountCents)
}
Output: JSON: 86 bytes, CBOR+toarray: 24 bytes (72% smaller) pay_abc123 4999
func (CBORCodec) Encode ¶
Encode marshals a value to canonical CBOR bytes with deterministic map ordering.
func (CBORCodec) EncodeToBuffer ¶
EncodeToBuffer writes canonical CBOR encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.
type CBORCompactCodec ¶
type CBORCompactCodec struct{}
CBORCompactCodec is an opt-in Codec that uses stricter decoding than CBORCodec. It uses CoreDetEncOptions (RFC 8949 "Core Deterministic") for encoding and ExtraReturnErrors(UnknownField) for decoding — rejecting unknown fields on decode as a schema drift detection mechanism.
This codec is NOT compatible with data written by CBORCodec (which uses CanonicalEncOptions with length-first sort). Use it only for new event stores.
For even smaller payloads, consumers should add `cbor:",toarray"` struct tags to their event payload types. This encodes structs as positional CBOR arrays instead of maps, eliminating field-name string keys (~30-40% reduction). The toarray tag is separate from this codec — the codec enables the strict encoding/decoding modes, and the consumer opts into per-type compactness.
type MyEvent struct {
_ struct{} `cbor:",toarray"`
ID string
Payload []byte
OccurredAt int64
}
Example ¶
ExampleCBORCompactCodec demonstrates the strict CBOR codec that rejects unknown fields on decode — a schema drift detection mechanism.
c := codec.CBORCompactCodec{}
type UserCreated struct {
Name string
Email string
}
data, _ := c.Encode(UserCreated{Name: testName, Email: testEmail})
var result UserCreated
_ = c.Decode(data, &result)
fmt.Println(result.Name, result.Email)
Output: Alice [email protected]
func (CBORCompactCodec) Decode ¶
func (CBORCompactCodec) Decode(data []byte, v any) error
Decode unmarshals compact CBOR bytes into a value. Returns an error if the data contains unknown fields (schema drift detection).
func (CBORCompactCodec) Encode ¶
func (CBORCompactCodec) Encode(v any) ([]byte, error)
Encode marshals a value to compact CBOR bytes with deterministic ordering.
func (CBORCompactCodec) EncodeToBuffer ¶
func (CBORCompactCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error
EncodeToBuffer writes compact CBOR encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.
func (CBORCompactCodec) Encoding ¶
func (CBORCompactCodec) Encoding() Encoding
type COSEEncrypt0 ¶
type COSEEncrypt0 struct {
// Protected contains the serialized protected header map (a CBOR-encoded map
// wrapped in a byte string). It is authenticated as additional data (AAD).
Protected []byte
// Unprotected contains header parameters that are not cryptographically
// protected, such as the initialization vector (IV).
Unprotected map[int64]any
// Ciphertext is the encrypted payload. It may be nil for detached content.
Ciphertext []byte
}
COSEEncrypt0 represents a COSE_Encrypt0 structure as defined in RFC 9052. It is a single-recipient encrypted message with protected headers, unprotected headers, and ciphertext.
func UnmarshalCOSEEncrypt0 ¶
func UnmarshalCOSEEncrypt0(data []byte) (COSEEncrypt0, error)
UnmarshalCOSEEncrypt0 decodes a COSE_Encrypt0 structure from CBOR bytes.
type COSESign1 ¶
type COSESign1 struct {
// Protected contains the serialized protected header map (a CBOR-encoded map
// wrapped in a byte string). It is stored as raw bytes so that signature
// verification can use the exact byte representation that was signed.
Protected []byte
// Unprotected contains header parameters that are not cryptographically
// protected, such as the key identifier (kid).
Unprotected map[int64]any
// Payload is the signed payload. It may be nil for detached content.
Payload []byte
// Signature is the raw cryptographic signature value.
Signature []byte
}
COSESign1 represents a COSE_Sign1 structure as defined in RFC 9052. It is a single-signer signed message with protected headers, unprotected headers, payload, and signature.
func UnmarshalCOSESign1 ¶
UnmarshalCOSESign1 decodes a COSE_Sign1 structure from CBOR bytes.
type Codec ¶
type Codec interface {
Encoding() Encoding
Encode(v any) ([]byte, error)
Decode(data []byte, v any) error
}
Codec serializes and deserializes values with a declared encoding.
func ForEncoding ¶
ForEncoding returns the built-in Codec for the given Encoding. It resolves EncodingJSON → JSONCodec, EncodingCBOR → CBORCodec, and EncodingRaw → RawCodec.
For unknown encodings (including custom values like "encrypted"), it returns ErrUnknownEncoding. Callers that need custom encoding support should build their own dispatch table.
ForEncoding is the codec-level counterpart to AutoDetect: AutoDetect infers the encoding from raw bytes, ForEncoding resolves a known encoding stamp to its codec. Together they enable mixed-stream decoding — see [event.DecodePayloadAuto].
Example (Classified) ¶
ExampleForEncoding_classified shows how to extract the stable code, behavioral family, and structured context from a codec error with errors.AsType. Every wrapping helper in this package returns classified errors — see the # Errors section of the package documentation and docs/error-codes.md.
package main
import (
"errors"
"fmt"
"github.com/larsartmann/go-codec"
errorfamily "github.com/larsartmann/go-error-family"
)
func main() {
_, err := codec.ForEncoding("encrypted") // no built-in codec matches
if e, ok := errors.AsType[*errorfamily.Error](err); ok {
fmt.Println("code:", e.Code())
fmt.Println("family:", e.ErrorFamily())
fmt.Println("encoding:", e.ErrorContext()["encoding"])
}
}
Output: code: codec.unknown_encoding family: rejection encoding: encrypted
func UnwrapDecode ¶
UnwrapDecode inspects data for an envelope wrapper. If found, it returns the stamped codec and inner data bytes. If not found (old unenveloped data), it returns the fallback codec and the original data unchanged.
This enables backward-compatible migration: old data decodes via the fallback, new data decodes via the stamped codec. Stores can gradually transition without a full clear-and-rebuild.
type CodecMetrics ¶ added in v0.2.0
type CodecMetrics struct {
// contains filtered or unexported fields
}
CodecMetrics records per-instance codec operation counters and last results. It is safe for concurrent use by multiple goroutines.
func (*CodecMetrics) Reset ¶ added in v0.2.0
func (m *CodecMetrics) Reset()
Reset clears all recorded metrics.
func (*CodecMetrics) Snapshot ¶ added in v0.2.0
func (m *CodecMetrics) Snapshot() MetricsSnapshot
Snapshot returns a point-in-time copy of the metrics.
type DetectionReason ¶ added in v0.2.0
type DetectionReason string
DetectionReason explains why AutoDetect chose an encoding.
const ( // DetectionReasonEmpty means the input was empty and defaulted to raw. DetectionReasonEmpty DetectionReason = "empty" // DetectionReasonCBORMajorType means the first byte identified a CBOR major type. DetectionReasonCBORMajorType DetectionReason = "cbor_major_type" // DetectionReasonJSONStructure means the first byte was an unambiguous JSON structural start. DetectionReasonJSONStructure DetectionReason = "json_structure" // DetectionReasonJSONTrialDecode means the first byte was ambiguous, but JSON trial decode succeeded. DetectionReasonJSONTrialDecode DetectionReason = "json_trial_decode" // DetectionReasonCBORTrialDecode means the first byte was ambiguous, JSON // trial decode failed, but CBOR trial decode succeeded. DetectionReasonCBORTrialDecode DetectionReason = "cbor_trial_decode" // DetectionReasonOversized means the payload exceeded maxAutoDetectSize and was treated as raw. DetectionReasonOversized DetectionReason = "oversized" // DetectionReasonUnknown means the payload did not match any known format. DetectionReasonUnknown DetectionReason = "unknown" )
type DeterministicCodec ¶ added in v0.2.0
type DeterministicCodec interface {
Codec
// contains filtered or unexported methods
}
DeterministicCodec is a marker interface implemented by codecs whose Encode produces byte-identical output for equal inputs on every call. Codecs that satisfy this interface are safe for cryptographic signing: the signing module can assert this at compile time, turning silent signature corruption (e.g. using JSONCodec in v1 mode, whose map key order is non-deterministic) into a build error.
The unexported method prevents external packages from implementing the interface — only the built-in codecs in this package can be signing-safe.
CBORCodec and CBORCompactCodec always implement DeterministicCodec. JSONCodec implements it only in the v2 build (encoding/json/v2 with Deterministic mode); the v1 default does not because map key ordering is non-deterministic. RawCodec never implements it because it performs no encoding at all.
Example ¶
ExampleDeterministicCodec shows how a signing helper can require a byte-deterministic codec at compile time. CBORCodec and CBORCompactCodec always satisfy the interface; JSONCodec satisfies it only in the GOEXPERIMENT=jsonv2 build; RawCodec never does.
sign := func(c codec.DeterministicCodec, v any) ([]byte, error) {
// Signing safety is guaranteed by the type: only codecs whose Encode
// is byte-deterministic can reach this body.
return c.Encode(v)
}
type User struct {
Name string
}
first, err := sign(codec.CBORCodec{}, User{Name: testName})
if err != nil {
fmt.Println("error:", err)
return
}
second, err := sign(codec.CBORCodec{}, User{Name: testName})
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(bytes.Equal(first, second))
// The following would NOT compile in the default (v1) build, because
// encoding/json v1 map key order is non-deterministic:
//
// _ = sign(codec.JSONCodec{}, User{Name: testName})
Output: true
type Encoding ¶
type Encoding string
Encoding identifies the serialization format used for a payload.
func AutoDetect ¶
AutoDetect inspects raw payload bytes and returns the most likely Encoding. It distinguishes JSON from CBOR by examining the structural first byte:
- JSON objects/arrays/strings start with '{', '[', or '"' (ASCII).
- CBOR maps (major type 5) start with 0xa0–0xbf; arrays (major type 4) with 0x80–0x9f. These ranges never overlap with valid JSON leading bytes.
For ambiguous leading bytes (e.g. bare numbers, booleans) the function falls back to a trial decode: JSON first, then CBOR.
Empty input returns EncodingRaw. Unknown data returns EncodingRaw.
AutoDetect is a best-effort heuristic for diagnostics and tooling — it is NOT a security boundary. Never use it to skip encoding validation; always pair detected data with the matching codec's Decode for authoritative parsing.
Example ¶
ExampleAutoDetect infers the encoding of unknown payload bytes from the leading byte. It is a best-effort heuristic for diagnostics and tooling — always pair the result with the matched codec's Decode for real work.
package main
import (
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
for _, data := range [][]byte{
[]byte(`{"name":"Alice"}`), // JSON object
{0xa1, 0x64, 'n', 'a', 'm', 'e', 0x65, 'A', 'l', 'i', 'c', 'e'}, // CBOR map
{0x1f}, // unrecognized
} {
fmt.Println(codec.AutoDetect(data))
}
}
Output: json cbor raw
type JSONCodec ¶
type JSONCodec struct{}
JSONCodec implements Codec using encoding/json.
Example ¶
c := codec.JSONCodec{}
type User struct {
Name string `json:"name"`
}
data, err := c.Encode(User{Name: testName})
if err != nil {
fmt.Println("error:", err)
return
}
var user User
err = c.Decode(data, &user)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(user.Name)
Output: Alice
func (JSONCodec) EncodeToBuffer ¶
EncodeToBuffer writes JSON encoding of v directly into buf, avoiding the allocation that Encode returns. Implements BufferEncoder.
type JSONDecoder ¶ added in v0.2.0
type JSONDecoder struct {
// contains filtered or unexported fields
}
JSONDecoder reads JSON values from an io.Reader. Each call to JSONDecoder.Decode reads one JSON value from the stream, skipping whitespace and newlines between values.
In the v2 build (GOEXPERIMENT=jsonv2), this wraps jsontext.Decoder with json.UnmarshalDecode for stateful streaming. json.UnmarshalRead is NOT used because it creates a new internal buffer per call, losing over-read bytes between values.
func NewJSONDecoder ¶ added in v0.2.0
func NewJSONDecoder(r io.Reader) *JSONDecoder
NewJSONDecoder creates a streaming JSON decoder that reads from r. Each call to JSONDecoder.Decode reads the next JSON value from the stream, skipping whitespace and newlines between values. Use for decoding large event batches from a stream without loading all bytes into memory.
Parity with NewCBORDecoder for consumers that standardize on JSON.
func (*JSONDecoder) Decode ¶ added in v0.2.0
func (d *JSONDecoder) Decode(v any) error
Decode reads the next JSON value from the stream into v.
type JSONEncoder ¶ added in v0.2.0
type JSONEncoder struct {
// contains filtered or unexported fields
}
JSONEncoder streams JSON values to an io.Writer. Each call to JSONEncoder.Encode writes one JSON value followed by a newline (NDJSON / JSON Lines convention), enabling a reader to consume values incrementally from the stream.
In the v2 build (GOEXPERIMENT=jsonv2), this uses json.MarshalWrite per value. jsontext.Encoder is intentionally NOT used because it inserts separator tokens between top-level values, corrupting NDJSON output.
func NewJSONEncoder ¶ added in v0.2.0
func NewJSONEncoder(w io.Writer) *JSONEncoder
NewJSONEncoder creates a streaming JSON encoder that writes to w. Each call to JSONEncoder.Encode writes one JSON value followed by a newline (NDJSON / JSON Lines convention), enabling incremental consumption on the reader side. Use for encoding large event batches without materializing the full byte slice in memory.
Parity with NewCBOREncoder for consumers that standardize on JSON.
Example ¶
ExampleNewJSONEncoder demonstrates streaming JSON encoding for large event batches using newline-delimited JSON (NDJSON). Each Encode call writes one JSON value followed by a newline, enabling incremental consumption on the reader side.
type Event struct {
Type string
Data string
}
var buf bytes.Buffer
enc := codec.NewJSONEncoder(&buf)
_ = enc.Encode(Event{Type: testEventType, Data: testUserName})
_ = enc.Encode(Event{Type: testEventType, Data: "bob"})
// Decode the NDJSON stream
dec := codec.NewJSONDecoder(&buf)
var events []Event
for {
var evt Event
if err := dec.Decode(&evt); err != nil {
break
}
events = append(events, evt)
}
fmt.Printf("%d events decoded from JSON stream\n", len(events))
Output: 2 events decoded from JSON stream
func (*JSONEncoder) Encode ¶ added in v0.2.0
func (e *JSONEncoder) Encode(v any) error
Encode writes the JSON encoding of v followed by a newline to the stream.
type MetricsHook ¶ added in v0.2.0
MetricsHook receives a notification after each observed operation. bytesProcessed is the length of the encoded payload for encodes or the input length for decodes. err is the result of the operation (nil on success).
Panic policy: hooks are caller-supplied callbacks and their panics PROPAGATE to the caller of Encode/Decode — they are not recovered. This is the idiomatic Go contract (a library must not swallow panics, which hides bugs). Metrics are always recorded BEFORE the hook runs, so a panicking hook leaves counters consistent. Keep hooks fast and panic-free: they execute inline on the codec's hot path.
Example ¶
ExampleMetricsHook demonstrates a dependency-free push-style metrics hook. The callback updates simple counters; in production, this is where you would emit to Prometheus, OpenTelemetry, or structured logs.
type event struct {
Type string
}
counters := map[codec.Operation]int64{}
obs := codec.ObserveCodec(codec.CBORCodec{},
codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, bytes int, err error) {
counters[op]++
}),
)
data, _ := obs.Encode(event{Type: testEventCreated})
var decoded event
_ = obs.Decode(data, &decoded)
fmt.Printf("encodes=%d decodes=%d type=%s\n",
counters[codec.OpEncode], counters[codec.OpDecode], decoded.Type)
Output: encodes=1 decodes=1 type=created
type MetricsSnapshot ¶ added in v0.2.0
type MetricsSnapshot struct {
EncodeCalls int64
EncodeBytes int64
EncodeErrors int64
LastEncodeError error
DecodeCalls int64
DecodeBytes int64
DecodeErrors int64
LastDecodeError error
}
MetricsSnapshot is a point-in-time copy of CodecMetrics.
Example ¶
ExampleMetricsSnapshot takes a point-in-time copy of ObservableCodec counters for operational dashboards. The snapshot is immutable — later codec operations do not change it.
type User struct {
Name string
}
obs := codec.ObserveCodec(codec.CBORCodec{})
for range 2 {
_, _ = obs.Encode(User{Name: testName})
}
snap := obs.Metrics().Snapshot()
fmt.Printf("encode calls: %d, encode errors: %d\n", snap.EncodeCalls, snap.EncodeErrors)
Output: encode calls: 2, encode errors: 0
type ObservableCodec ¶ added in v0.2.0
type ObservableCodec struct {
// contains filtered or unexported fields
}
ObservableCodec wraps a Codec and records metrics for every operation. It implements Codec and, when the wrapped codec implements BufferEncoder, BufferEncoder as well.
func ObserveCodec ¶ added in v0.2.0
func ObserveCodec(c Codec, opts ...ObserveOption) *ObservableCodec
ObserveCodec returns an observable wrapper around c.
Example ¶
ExampleObserveCodec demonstrates wrapping a codec with telemetry. The ObservableCodec decorator records per-operation metrics and invokes a MetricsHook after every encode/decode — useful for Prometheus or OpenTelemetry-style push telemetry without polling.
obs := codec.ObserveCodec(codec.CBORCodec{},
codec.WithMetricsHook(func(op codec.Operation, enc codec.Encoding, bytes int, err error) {
fmt.Printf("op=%d enc=%s err=%v\n", op, enc, err)
}))
data, _ := obs.Encode(map[string]string{testFieldName: testName})
var decoded map[string]string
_ = obs.Decode(data, &decoded)
m := obs.Metrics().Snapshot()
fmt.Printf("encode calls: %d, decode calls: %d\n", m.EncodeCalls, m.DecodeCalls)
Output: op=0 enc=cbor err=<nil> op=1 enc=cbor err=<nil> encode calls: 1, decode calls: 1
func (*ObservableCodec) Decode ¶ added in v0.2.0
func (obs *ObservableCodec) Decode(data []byte, v any) error
Decode unmarshals data and records metrics.
func (*ObservableCodec) Encode ¶ added in v0.2.0
func (obs *ObservableCodec) Encode(v any) ([]byte, error)
Encode marshals v and records metrics.
func (*ObservableCodec) EncodeToBuffer ¶ added in v0.2.0
func (obs *ObservableCodec) EncodeToBuffer(v any, buf *bytes.Buffer) error
EncodeToBuffer writes v into buf using the wrapped codec if it implements BufferEncoder; otherwise it encodes and writes the bytes.
func (*ObservableCodec) Encoding ¶ added in v0.2.0
func (obs *ObservableCodec) Encoding() Encoding
Encoding returns the wrapped codec's encoding.
func (*ObservableCodec) Metrics ¶ added in v0.2.0
func (obs *ObservableCodec) Metrics() *CodecMetrics
Metrics returns the live metrics sink for this wrapper.
type ObserveOption ¶ added in v0.2.0
type ObserveOption func(*ObservableCodec)
ObserveOption configures an ObservableCodec.
func WithMetrics ¶ added in v0.2.0
func WithMetrics(metrics *CodecMetrics) ObserveOption
WithMetrics stores metrics in the supplied CodecMetrics instead of creating a private one. This lets multiple ObservableCodecs share a metrics sink or lets callers inspect metrics directly.
func WithMetricsHook ¶ added in v0.2.0
func WithMetricsHook(hook MetricsHook) ObserveOption
WithMetricsHook registers a hook that is called after every Encode/Decode.
type Operation ¶ added in v0.2.0
type Operation int
Operation identifies the kind of observed codec operation.
type RawCodec ¶
type RawCodec struct{}
RawCodec implements Codec as a passthrough for []byte. Encode accepts only []byte (or json.RawMessage). Decode copies data into a *[]byte target.
Example ¶
package main
import (
"fmt"
"github.com/larsartmann/go-codec"
)
func main() {
c := codec.RawCodec{}
raw := []byte(`{"name":"Bob"}`)
data, err := c.Encode(raw)
if err != nil {
fmt.Println("error:", err)
return
}
var decoded []byte
err = c.Decode(data, &decoded)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(decoded))
}
Output: {"name":"Bob"}
type SizeResult ¶ added in v0.2.0
SizeResult reports the serialized byte sizes of a value under each codec.
func Size ¶
func Size(v any) SizeResult
Size encodes v with both JSON and CBOR and returns the byte sizes. This is useful for deciding whether switching a payload type from JSON to CBOR is worthwhile before committing to a format change.
If a codec fails to encode v, that size is reported as -1.
s := codec.Size(UserCreated{Name: "Alice", Email: "[email protected]"})
savings := float64(s.JSON-s.CBOR) / float64(s.JSON) * 100 // e.g. 19
Example ¶
ExampleSize compares the serialized byte sizes of a value under JSON and CBOR, helping decide whether a format switch is worthwhile before committing.
type UserCreated struct {
Name string
Email string
}
s := codec.Size(UserCreated{Name: testName, Email: testEmail})
if s.CBOR < s.JSON {
fmt.Printf("CBOR saves %d bytes (%.0f%% smaller)\n",
s.JSON-s.CBOR,
float64(s.JSON-s.CBOR)/float64(s.JSON)*100)
} else {
fmt.Println("CBOR is not smaller for this payload")
}
Output: CBOR saves 8 bytes (18% smaller)