codec

package
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Gob = gobCodec{}

Gob is a simple encoder and decoder that uses the gob package.

View Source
var JSON = jsonCodec{}

JSON is a simple JSON encoder and decoder.

View Source
var Protobuf = protobuf{}

Protobuf encodes and decodes messages using protocol buffers.

Functions

func NewCodecMiddleware

func NewCodecMiddleware(broker pubsub.Broker, codec Codec) pubsub.Broker

NewCodecMiddleware creates a new Codec middleware that encodes/decodes messages when publishing and delivering.

When Publishing

Intercepts each message being published and encodes it before passing it to wrapped broker.

When Delivering

Intercepts each message before it gets delivered to subscriber handlers and decodes into handler's accepted type assuming that the incoming message is a byte slice (`[]byte`)

Decoder function is invoked once for each destination type, and it takes two arguments:

1. The raw message as a byte slice 2. A pointer to a variable of type of handler's desired type.

For example, given the following handler functions:

S1: func (ctx context.Context, msg string) error
S2: func (ctx context.Context, msg string) error
S3: func (ctx context.Context, msg map[string]string) error

Then, decoder function will be invoked twice, once for each type:

- `string` - `map[string]string`

If decoder is unable to convert the given byte slice into the desired type (string or map in the above example), an error must be returned by Codec implementations. This will prevent from delivering the message to underlying handler.

Performance Considerations:

Message decoding are expensive operations as interception takes place each time a message is delivered to handler function. This may produce unnecessary decoding operation when the same message is delivered to multiple subscriptions.

To address this issue, this middleware uses a small in-memory LRU cache of each seen decoded message to prevent from decoding the same message multiple times.

Types

type Codec

type Codec interface {
	Encode(interface{}) ([]byte, error)
	Decode([]byte, interface{}) error
}

Codec represents a component that can encode and decode messages.

var Msgpack Codec = msgpackCodec{}

Msgpack is a simple encoder and decoder that uses the msgpack package. See: https://github.com/vmihailenco/msgpack

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL