amqp

package
Version: v0.0.0-...-e2fa36f Latest Latest
Warning

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

Go to latest
Published: May 27, 2022 License: Apache-2.0 Imports: 11 Imported by: 1

Documentation

Overview

Package amqp encodes and decodes AMQP 1.0 messages and data types as Go types.

It follows the standard 'encoding' libraries pattern. The mapping between AMQP and Go types is described in the documentation of the Marshal and Unmarshal functions.

This package requires the [proton-C library](http://qpid.apache.org/proton) to be installed.

Package 'electron' is a full AMQP 1.0 client/server toolkit using this package.

AMQP 1.0 is an open standard for inter-operable message exchange, see <http://www.amqp.org/>

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	InternalError         = "amqp:internal-error"
	NotFound              = "amqp:not-found"
	UnauthorizedAccess    = "amqp:unauthorized-access"
	DecodeError           = "amqp:decode-error"
	ResourceLimitExceeded = "amqp:resource-limit-exceeded"
	NotAllowed            = "amqp:not-allowed"
	InvalidField          = "amqp:invalid-field"
	NotImplemented        = "amqp:not-implemented"
	ResourceLocked        = "amqp:resource-locked"
	PreconditionFailed    = "amqp:precondition-failed"
	ResourceDeleted       = "amqp:resource-deleted"
	IllegalState          = "amqp:illegal-state"
	FrameSizeTooSmall     = "amqp:frame-size-too-small"
)
View Source
var EndOfData = &UnmarshalError{s: "Not enough data for AMQP value"}

Error returned if there are not enough bytes to decode a complete AMQP value.

Functions

func Marshal

func Marshal(v interface{}, buffer []byte) (outbuf []byte, err error)

func MarshalUnsafe

func MarshalUnsafe(v interface{}, pnData unsafe.Pointer) (err error)

Internal use only

func ParseURL

func ParseURL(s string) (u *url.URL, err error)

ParseUrl parses an AMQP URL string and returns a net/url.Url.

It is more forgiving than net/url.Parse and allows most of the parts of the URL to be missing, assuming AMQP defaults.

Example
for _, s := range []string{
	"amqp://username:password@host:1234/path",
	"host:1234",
	"host",
	"host/path",
	"amqps://host",
	"/path",
	"",
} {
	u, err := ParseURL(s)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(u)
	}
}
Output:

amqp://username:password@host:1234/path
amqp://host:1234
amqp://host:amqp
amqp://host:amqp/path
amqps://host:amqps
amqp://localhost:amqp/path
amqp://localhost:amqp

func PnError

func PnError(e *C.pn_error_t) error

func Unmarshal

func Unmarshal(bytes []byte, v interface{}) (n int, err error)

Unmarshal decodes AMQP-encoded bytes and stores the result in the Go value pointed to by v. Legal conversions from the source AMQP type to the target Go type as follows:

+----------------------------+-------------------------------------------------+
|Target Go type              | Allowed AMQP types
+============================+==================================================+
|bool                        |bool                                              |
+----------------------------+--------------------------------------------------+
|int, int8, int16, int32,    |Equivalent or smaller signed integer type:        |
|int64                       |byte, short, int, long or char                    |
+----------------------------+--------------------------------------------------+
|uint, uint8, uint16, uint32,|Equivalent or smaller unsigned integer type:      |
|uint64                      |ubyte, ushort, uint, ulong                        |
+----------------------------+--------------------------------------------------+
|float32, float64            |Equivalent or smaller float or double             |
+----------------------------+--------------------------------------------------+
|string, []byte              |string, symbol or binary                          |
+----------------------------+--------------------------------------------------+
|Symbol                      |symbol                                            |
+----------------------------+--------------------------------------------------+
|Char                        |char                                              |
+----------------------------+--------------------------------------------------+
|Described                   |AMQP described type [1]                           |
+----------------------------+--------------------------------------------------+
|Time                        |timestamp                                         |
+----------------------------+--------------------------------------------------+
|UUID                        |uuid                                              |
+----------------------------+--------------------------------------------------+
|map[interface{}]interface{} |Any AMQP map                                      |
+----------------------------+--------------------------------------------------+
|map[K]T                     |map, provided all keys and values can unmarshal   |
|                            |to types K,T                                      |
+----------------------------+--------------------------------------------------+
|[]interface{}               |AMQP list or array                                |
+----------------------------+--------------------------------------------------+
|[]T                         |list or array if elements can unmarshal as T      |
+----------------------------+------------------n-------------------------------+
|interface{}                 |any AMQP type[2]                                  |
+----------------------------+--------------------------------------------------+

[1] An AMQP described value can also unmarshal to a plain value, discarding the descriptor. Unmarshalling into the special amqp.Described type preserves the descriptor.

[2] Any AMQP value can be unmarshalled to an interface{}. The Go type is determined by the AMQP type as follows:

+----------------------------+--------------------------------------------------+
|Source AMQP Type            |Go Type in target interface{}                     |
+============================+==================================================+
|bool                        |bool                                              |
+----------------------------+--------------------------------------------------+
|byte,short,int,long         |int8,int16,int32,int64                            |
+----------------------------+--------------------------------------------------+
|ubyte,ushort,uint,ulong     |uint8,uint16,uint32,uint64                        |
+----------------------------+--------------------------------------------------+
|float, double               |float32, float64                                  |
+----------------------------+--------------------------------------------------+
|string                      |string                                            |
+----------------------------+--------------------------------------------------+
|symbol                      |Symbol                                            |
+----------------------------+--------------------------------------------------+
|char                        |Char                                              |
+----------------------------+--------------------------------------------------+
|binary                      |Binary                                            |
+----------------------------+--------------------------------------------------+
|null                        |nil                                               |
+----------------------------+--------------------------------------------------+
|described type              |Described                                         |
+----------------------------+--------------------------------------------------+
|timestamp                   |time.Time                                         |
+----------------------------+--------------------------------------------------+
|uuid                        |UUID                                              |
+----------------------------+--------------------------------------------------+
|map                         |Map or AnyMap[4]                                  |
+----------------------------+--------------------------------------------------+
|list                        |List                                              |
+----------------------------+--------------------------------------------------+
|array                       |[]T for simple types, T is chosen as above [3]    |
+----------------------------+--------------------------------------------------+

[3] An AMQP array of simple types unmarshalls as a slice of the corresponding Go type. An AMQP array containing complex types (lists, maps or nested arrays) unmarshals to the generic array type amqp.Array

[4] An AMQP map unmarshals as the generic `type Map map[interface{}]interface{}` unless it contains key values that are illegal as Go map types, in which case it unmarshals as type AnyMap.

The following Go types cannot be unmarshaled: uintptr, function, interface, channel, array (use slice), struct

AMQP types not yet supported: decimal32/64/128

func UnmarshalUnsafe

func UnmarshalUnsafe(pnData unsafe.Pointer, v interface{}) (err error)

Internal

func UpdateURL

func UpdateURL(in *url.URL) (err error)

Types

type AnnotationKey

type AnnotationKey struct {
	// contains filtered or unexported fields
}

AnnotationKey is used as a map key for AMQP annotation maps which are allowed to have keys that are either symbol or ulong but no other type.

Example
var k AnnotationKey = AnnotationKeySymbol(Symbol("foo"))
fmt.Println(k.Get().(Symbol))
k = AnnotationKeyUint64(42)
fmt.Println(k.Get().(uint64))
Output:

foo
42

func AnnotationKeyString

func AnnotationKeyString(v string) AnnotationKey

func AnnotationKeySymbol

func AnnotationKeySymbol(v Symbol) AnnotationKey

func AnnotationKeyUint64

func AnnotationKeyUint64(v uint64) AnnotationKey

func (AnnotationKey) Get

func (k AnnotationKey) Get() interface{}

Returns the value which must be Symbol, uint64 or nil

func (AnnotationKey) String

func (k AnnotationKey) String() string

type AnyMap

type AnyMap []KeyValue

The most general AMQP map type, for unusual interoperability cases.

This is not a Go Map but a sequence of {key, value} pairs.

An AnyMap lets you control or examine the encoded ordering of key,value pairs and use key values that are not legal as Go map keys.

The amqp.Map, or plain Go map types are easier to use for most cases.

func (AnyMap) Map

func (a AnyMap) Map() (m Map)

Return a Map constructed from an AnyMap. Panic if the AnyMap has key values that are not valid Go map keys (e.g. maps, slices)

type Array

type Array []interface{}

The generic AMQP array type, used to unmarshal an array with nested array, map or list elements. Arrays of simple type T unmarshal to []T

type Binary

type Binary string

Binary is a string that is encoded as an AMQP binary. It is a string rather than a byte[] because byte[] is not hashable and can't be used as a map key, AMQP frequently uses binary types as map keys. It can convert to and from []byte

func (Binary) GoString

func (b Binary) GoString() string

func (Binary) String

func (b Binary) String() string

type Char

type Char rune

Char is an AMQP unicode character, equivalent to a Go rune. It is defined as a distinct type so it can be distinguished from an AMQP int

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder decodes AMQP values from an io.Reader.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

The decoder has it's own buffer and may read more data than required for the AMQP values requested. Use Buffered to see if there is data left in the buffer.

func (*Decoder) Buffered

func (d *Decoder) Buffered() io.Reader

Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode.

func (*Decoder) Decode

func (d *Decoder) Decode(v interface{}) (err error)

Decode reads the next AMQP value from the Reader and stores it in the value pointed to by v.

See the documentation for Unmarshal for details about the conversion of AMQP into a Go value.

type Described

type Described struct {
	Descriptor interface{}
	Value      interface{}
}

Described represents an AMQP described type, which is really just a pair of AMQP values - the first is treated as a "descriptor", and is normally a string or ulong providing information about the type. The second is the "value" and can be any AMQP value.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder encodes AMQP values to an io.Writer

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

New encoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (e *Encoder) Encode(v interface{}) (err error)

type Error

type Error struct{ Name, Description string }

Error is an AMQP error condition. It has a name and a description. It implements the Go error interface so can be returned as an error value.

You can pass amqp.Error to methods that send an error to a remote endpoint, this gives you full control over what the remote endpoint will see.

You can also pass any Go error to such functions, the remote peer will see the equivalent of MakeError(error)

func Errorf

func Errorf(name, format string, arg ...interface{}) Error

Errorf makes a Error with name and formatted description as per fmt.Sprintf

func MakeError

func MakeError(err error) Error

MakeError makes an AMQP error from a go error: {Name: InternalError, Description: err.Error()} If err is already an amqp.Error it is returned unchanged.

func (Error) Error

func (c Error) Error() string

Error implements the Go error interface for AMQP error errors.

type KeyValue

type KeyValue struct{ Key, Value interface{} }

KeyValue pair, used by AnyMap

type List

type List []interface{}

The AMQP list type. A generic list that can hold mixed-type values.

func (List) GoString

func (l List) GoString() string

GoString for List prints values with their types, useful for debugging.

type Map

type Map map[interface{}]interface{}

The AMQP map type. A generic map that can have mixed-type keys and values.

func (Map) GoString

func (m Map) GoString() string

GoString for Map prints values with their types, useful for debugging.

type MarshalError

type MarshalError struct {
	// The Go type.
	GoType reflect.Type
	// contains filtered or unexported fields
}

Error returned if Go data cannot be marshaled as an AMQP type.

func (MarshalError) Error

func (e MarshalError) Error() string

type Message

type Message interface {
	// Durable indicates that any parties taking responsibility
	// for the message must durably store the content.
	Durable() bool
	SetDurable(bool)

	// Priority impacts ordering guarantees. Within a
	// given ordered context, higher priority messages may jump ahead of
	// lower priority messages.
	Priority() uint8
	SetPriority(uint8)

	// TTL or Time To Live, a message it may be dropped after this duration
	TTL() time.Duration
	SetTTL(time.Duration)

	// FirstAcquirer indicates
	// that the recipient of the message is the first recipient to acquire
	// the message, i.e. there have been no failed delivery attempts to
	// other acquirers. Note that this does not mean the message has not
	// been delivered to, but not acquired, by other recipients.
	FirstAcquirer() bool
	SetFirstAcquirer(bool)

	// DeliveryCount tracks how many attempts have been made to
	// delivery a message.
	DeliveryCount() uint32
	SetDeliveryCount(uint32)

	// MessageId provides a unique identifier for a message.
	// it can be an a string, an unsigned long, a uuid or a
	// binary value.
	MessageId() interface{}
	SetMessageId(interface{})

	UserId() string
	SetUserId(string)

	Address() string
	SetAddress(string)

	Subject() string
	SetSubject(string)

	ReplyTo() string
	SetReplyTo(string)

	// CorrelationId is set on correlated request and response messages. It can be
	// an a string, an unsigned long, a uuid or a binary value.
	CorrelationId() interface{}
	SetCorrelationId(interface{})

	ContentType() string
	SetContentType(string)

	ContentEncoding() string
	SetContentEncoding(string)

	// ExpiryTime indicates an absolute time when the message may be dropped.
	// A Zero time (i.e. t.isZero() == true) indicates a message never expires.
	ExpiryTime() time.Time
	SetExpiryTime(time.Time)

	CreationTime() time.Time
	SetCreationTime(time.Time)

	GroupId() string
	SetGroupId(string)

	GroupSequence() int32
	SetGroupSequence(int32)

	ReplyToGroupId() string
	SetReplyToGroupId(string)

	// Properties set by the application to be carried with the message.
	// Values must be simple types (not maps, lists or sequences)
	ApplicationProperties() map[string]interface{}
	SetApplicationProperties(map[string]interface{})

	// Per-delivery annotations to provide delivery instructions.
	// May be added or removed by intermediaries during delivery.
	// See ApplicationProperties() for properties set by the application.
	DeliveryAnnotations() map[AnnotationKey]interface{}
	SetDeliveryAnnotations(map[AnnotationKey]interface{})

	// Message annotations added as part of the bare message at creation, usually
	// by an AMQP library. See ApplicationProperties() for properties set by the application.
	MessageAnnotations() map[AnnotationKey]interface{}
	SetMessageAnnotations(map[AnnotationKey]interface{})

	// Inferred indicates how the message content
	// is encoded into AMQP sections. If inferred is true then binary and
	// list values in the body of the message will be encoded as AMQP DATA
	// and AMQP SEQUENCE sections, respectively. If inferred is false,
	// then all values in the body of the message will be encoded as AMQP
	// VALUE sections regardless of their type.
	Inferred() bool
	SetInferred(bool)

	// Get the message body, using the amqp.Unmarshal() rules for interface{}
	Body() interface{}

	// Set the body using amqp.Marshal()
	SetBody(interface{})

	// Marshal a Go value into the message body, synonym for SetBody()
	Marshal(interface{})

	// Unmarshal the message body, using amqp.Unmarshal()
	Unmarshal(interface{})

	// Encode encodes the message as AMQP data. If buffer is non-nil and is large enough
	// the message is encoded into it, otherwise a new buffer is created.
	// Returns the buffer containing the message.
	Encode(buffer []byte) ([]byte, error)

	// Decode data into this message. Overwrites an existing message content.
	Decode(buffer []byte) error

	// Clear the message contents, set all fields to the default value.
	Clear()

	// Copy the contents of another message to this one.
	Copy(m Message) error

	// Deprecated: use DeliveryAnnotations() for a more type-safe interface
	Instructions() map[string]interface{}
	SetInstructions(v map[string]interface{})

	// Deprecated: use MessageAnnotations() for a more type-safe interface
	Annotations() map[string]interface{}
	SetAnnotations(v map[string]interface{})

	// Deprecated: use ApplicationProperties() for a more type-safe interface
	Properties() map[string]interface{}
	SetProperties(v map[string]interface{})

	// Human-readable string showing message contents and properties
	String() string
}

Message is the interface to an AMQP message.

func DecodeMessage

func DecodeMessage(data []byte) (m Message, err error)

func NewMessage

func NewMessage() Message

NewMessage creates a new message instance.

func NewMessageCopy

func NewMessageCopy(m Message) Message

NewMessageCopy creates a copy of an existing message.

func NewMessageWith

func NewMessageWith(value interface{}) Message

NewMessageWith creates a message with value as the body.

type MessageCodec

type MessageCodec struct {

	// Optionally remember a byte buffer to use with MessageCodec methods.
	Buffer []byte
	// contains filtered or unexported fields
}

Internal use only

func (*MessageCodec) Close

func (mc *MessageCodec) Close()

func (*MessageCodec) Decode

func (mc *MessageCodec) Decode(m Message, data []byte) error

func (*MessageCodec) Encode

func (mc *MessageCodec) Encode(m Message, buffer []byte) ([]byte, error)

Encode m using buffer. Return the final buffer used to hold m, may be different if the initial buffer was not large enough.

type PnErrorCode

type PnErrorCode int

func (PnErrorCode) String

func (e PnErrorCode) String() string

type Symbol

type Symbol string

Symbol is a string that is encoded as an AMQP symbol

func (Symbol) GoString

func (s Symbol) GoString() string

func (Symbol) String

func (s Symbol) String() string

type UUID

type UUID [16]byte

UUID is an AMQP 128-bit Universally Unique Identifier, as defined by RFC-4122 section 4.1.2

func (UUID) String

func (u UUID) String() string

type UnmarshalError

type UnmarshalError struct {
	// The name of the AMQP type.
	AMQPType string
	// The Go type.
	GoType reflect.Type
	// contains filtered or unexported fields
}

Error returned if AMQP data cannot be unmarshaled as the desired Go type.

func (UnmarshalError) Error

func (e UnmarshalError) Error() string

Jump to

Keyboard shortcuts

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