JSON Registry
The json.Registry implements event.Registry using JSON serialization with envelope wrapping and upcaster-based schema evolution.
Setup
import eventjson "github.com/isaquesb/go-event-bus/json"
registry := eventjson.NewRegistry()
// Register event factories with their version
registry.Register("user.created", func() event.Event { return &UserCreated{} }, 1)
registry.Register("user.created", func() event.Event { return &UserCreatedV2{} }, 2)
// Register upcasters for schema migration
registry.RegisterUpcaster(&UserCreatedV1ToV2{})
Register
registry.Register(name string, factory event.Factory, version int)
Registers an event factory for a given name and version. The registry tracks the latest version for each event name.
Encode
data, err := registry.Encode(ctx, event)
- Marshals the event to JSON
- Detects version (via
WithVersionor defaults to 1) - Extracts trace context from the current span
- Wraps everything in an
Envelope - Marshals the envelope to JSON
Decode
ctx, event, err := registry.Decode(ctx, data)
- Unmarshals the envelope
- Restores trace context if
trace_idandspan_idare present - Runs upcaster chain if the version is not the latest
- Creates the event via the factory for the latest version
- Unmarshals the payload into the event
Trace Propagation
The registry automatically:
- On Encode: Extracts
TraceIDandSpanIDfrom the current OpenTelemetry span context - On Decode: Restores the remote span context, enabling trace correlation across transport boundaries