stomp: github.com/jjeffery/stomp Index | Examples | Files | Directories

package stomp

import "github.com/jjeffery/stomp"

Package stomp provides operations that allow communication with a message broker that supports the STOMP protocol. STOMP is the Streaming Text-Oriented Messaging Protocol. See http://stomp.github.com/ for more details.

This package provides support for all STOMP protocol features in the STOMP protocol specifications, versions 1.0, 1.1 and 1.2. These features including protocol negotiation, heart-beating, value encoding, and graceful shutdown.

Connecting to a STOMP server is achieved using the stomp.Dial function, or the stomp.Connect function. See the examples section for a summary of how to use these functions. Both functions return a stomp.Conn object for subsequent interaction with the STOMP server.

Once a connection (stomp.Conn) is created, it can be used to send messages to the STOMP server, or create subscriptions for receiving messages from the STOMP server. Transactions can be created to send multiple messages and/ or acknowledge multiple received messages from the server in one, atomic transaction. The examples section has examples of using subscriptions and transactions.

The client program can instruct the stomp.Conn to gracefully disconnect from the STOMP server using the Disconnect method. This will perform a graceful shutdown sequence as specified in the STOMP specification.

This package also exports types that represent a STOMP frame, and operate on STOMP frames. These types include stomp.Frame, stomp.Reader, stomp.Writer and stomp.Validator. While a program can use this package to communicate with a STOMP server without using these types directly, they are useful for implementing a STOMP server in go.

The server subpackage provides a simple implementation of a STOMP server that is useful for testing and could be useful for applications that require a simple, STOMP-compliant message broker.

Index

Examples

Package Files

ack.go conn.go encode.go errors.go frame.go header.go id.go message.go reader.go stomp.go subscription.go transaction.go validator.go version.go writer.go

Constants

const DefaultReadHeartBeatError = 5 * time.Second

Default time span to add to read/write heart-beat timeouts to avoid premature disconnections due to network latency.

type AckMode

type AckMode int

The AckMode type is an enumeration of the acknowledgement modes for a STOMP subscription.

const (
    // No acknowledgement is required, the server assumes that the client
    // received the message.
    AckAuto AckMode = iota

    // Client acknowledges messages. When a client acknowledges a message,
    // any previously received messages are also acknowledged.
    AckClient

    // Client acknowledges message. Each message is acknowledged individually.
    AckClientIndividual
)

func (AckMode) ShouldAck

func (a AckMode) ShouldAck() bool

ShouldAck returns true if this AckMode is an acknowledgement mode which requires acknowledgement. Returns true for all values except AckAuto, which returns false.

func (AckMode) String

func (a AckMode) String() string

String returns the string representation of the AckMode value.

type Conn

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

A Conn is a connection to a STOMP server. Create a Conn using either the Dial or Connect function.

func Connect

func Connect(conn io.ReadWriteCloser, opts Options) (*Conn, error)

Connect creates a STOMP connection and performs the STOMP connect protocol sequence. The connection to the STOMP server has already been created by the program. The opts parameter provides the opportunity to specify STOMP protocol options.

Example of connecting to a STOMP server using an existing network connection.

Code:

netConn, err := net.DialTimeout("tcp", "stomp.server.com:61613", 10*time.Second)
if err != nil {
    return err
}

stompConn, err := stomp.Connect(netConn, stomp.Options{})
if err != nil {
    return err
}

defer stompConn.Disconnect()

doSomethingWith(stompConn)
return nil

func Dial

func Dial(network, addr string, opts Options) (*Conn, error)

Dial creates a network connection to a STOMP server and performs the STOMP connect protocol sequence. The network endpoint of the STOMP server is specified by network and addr. STOMP protocol options can be specified in opts.

Connect to a STOMP server using default options.

Code:play 

conn, err := stomp.Dial("tcp", "192.168.1.1:61613", stomp.Options{})
if err != nil {
    return err
}

err = conn.Send(
    "/queue/test-1",           // destination
    "text/plain",              // content-type
    []byte("Test message #1"), // body
    nil) // no headers
if err != nil {
    return err
}

return conn.Disconnect()

Connect to a STOMP server that requires authentication. In addition, we are only prepared to use STOMP protocol version 1.1 or 1.2, and the virtual host is named "dragon". In this example the STOMP server also accepts a non-standard header called 'nonce'.

Code:play 

conn, err := stomp.Dial("tcp", "192.168.1.1:61613", stomp.Options{
    Login:         "scott",
    Passcode:      "leopard",
    AcceptVersion: "1.1,1.2",
    Host:          "dragon",
    NonStandard:   stomp.NewHeader("nonce", "B256B26D320A"),
})
if err != nil {
    return err
}

err = conn.Send(
    "/queue/test-1",           // destination
    "text/plain",              // content-type
    []byte("Test message #1"), // body
    nil) // no optional headers
if err != nil {
    return err
}

return conn.Disconnect()

func (*Conn) Ack

func (c *Conn) Ack(m *Message) error

Ack acknowledges a message received from the STOMP server. If the message was received on a subscription with AckMode == AckAuto, then no operation is performed.

func (*Conn) Begin

func (c *Conn) Begin() *Transaction

Begin is used to start a transaction. Transactions apply to sending and acknowledging. Any messages sent or acknowledged during a transaction will be processed atomically by the STOMP server based on the transaction.

func (*Conn) Disconnect

func (c *Conn) Disconnect() error

Disconnect will disconnect from the STOMP server. This function follows the STOMP standard's recommended protocol for graceful disconnection: it sends a DISCONNECT frame with a receipt header element. Once the RECEIPT frame has been received, the connection with the STOMP server is closed and any further attempt to write to the server will fail.

func (*Conn) Nack

func (c *Conn) Nack(m *Message) error

func (*Conn) Send

func (c *Conn) Send(destination, contentType string, body []byte, userDefined *Header) error

Send sends a message to the STOMP server, which in turn sends the message to the specified destination. This method returns without confirming that the STOMP server has received the message. If the STOMP server does fail to receive the message for any reason, the connection will close.

The content type should be specified, according to the STOMP specification, but if contentType is an empty string, the message will be delivered without a content type header entry. The body array contains the message body, and its content should be consistent with the specified content type.

The message can contain optional, user-defined header entries in userDefined. If there are no optional header entries, then set userDefined to nil.

Code:play 

// send with receipt and an optional header
err := c.Send(
    "/queue/test-1",            // destination
    "text/plain",               // content-type
    []byte("Message number 1"), // body
    stomp.NewHeader("expires", "2020-12-31 23:59:59"))
if err != nil {
    return err
}

// send with no receipt and no optional headers
err = c.Send("/queue/test-2", "application/xml",
    []byte("<message>hello</message>"), nil)
if err != nil {
    return err
}

return nil

func (*Conn) SendWithReceipt

func (c *Conn) SendWithReceipt(destination, contentType string, body []byte, userDefined *Header) error

Send sends a message to the STOMP server, which in turn sends the message to the specified destination. This method does not return until the STOMP server has confirmed receipt of the message.

The content type should be specified, according to the STOMP specification, but if contentType is an empty string, the message will be delivered without a content type header entry. The body array contains the message body, and its content should be consistent with the specified content type.

The message can contain optional, user-defined header entries in userDefined. If there are no optional header entries, then set userDefined to nil.

func (*Conn) Server

func (c *Conn) Server() string

Server returns the STOMP server identification, which can be returned by the STOMP server during the connect sequence. If the STOMP server does not return a server header entry, this value will be a blank string.

func (*Conn) Session

func (c *Conn) Session() string

Session returns the session identifier, which can be returned by the STOMP server during the connect sequence. If the STOMP server does not return a session header entry, this value will be a blank string.

func (*Conn) Subscribe

func (c *Conn) Subscribe(destination string, ack AckMode) (*Subscription, error)

Subscribe creates a subscription on the STOMP server. The subscription has a destination, and messages sent to that destination will be received by this subscription. A subscription has a channel on which the calling program can receive messages.

func (*Conn) SubscribeWithHeaders

func (c *Conn) SubscribeWithHeaders(destination string, ack AckMode, headers *Header) (*Subscription, error)

SubscribeWithHeaders is similar to Subscribe, but also sends optional headers with the subscription.

func (*Conn) Version

func (c *Conn) Version() Version

Version returns the version of the STOMP protocol that is being used to communicate with the STOMP server. This version is negotiated with the server during the connect sequence.

type Error

type Error struct {
    Message string
    Frame   *Frame
}

StompError implements the Error interface, and provides additional information about a STOMP error.

func (Error) Error

func (e Error) Error() string

type Frame

type Frame struct {
    Command string
    *Header
    Body []byte
}

A Frame represents a STOMP frame. A frame consists of a command followed by a collection of header elements, and then an optional body.

Users of this package will not normally need to make use of the Frame type directly. It is a lower level type useful for implementing STOMP protocol handlers.

func NewFrame

func NewFrame(command string, headers ...string) *Frame

NewFrame creates a new STOMP frame with the specified command and headers. The headers should contain an even number of entries. Each even index is the header name, and the odd indexes are the assocated header values.

Creates a STOMP frame.

Code:

/*
	Creates a STOMP frame that looks like the following:

		CONNECT
		login:scott
		passcode:tiger
		host:stompserver
		accept-version:1.1,1.2

		^@
*/
f := stomp.NewFrame("CONNECT",
    "login", "scott",
    "passcode", "tiger",
    "host", "stompserver",
    "accept-version", "1.1,1.2")
doSomethingWith(f)

func (*Frame) Clone

func (f *Frame) Clone() *Frame

Clone creates a deep copy of the frame and its header. The cloned frame shares the body with the original frame.

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

A Header represents the header part of a STOMP frame. The header in a STOMP frame consists of a list of header entries. Each header entry is a key/value pair of strings.

Normally a STOMP header only has one header entry for a given key, but the STOMP standard does allow for multiple header entries with the same key. In this case, the first header entry contains the value, and any subsequent header entries with the same key are ignored.

Example header containing 6 header entries. Note that the second header entry with the key "comment" would be ignored.

login:scott
passcode:tiger
host:stompserver
accept-version:1.0,1.1,1.2
comment:some comment
comment:another comment

func NewHeader

func NewHeader(headerEntries ...string) *Header

NewHeader creates a new Header and populates it with header entries. This function expects an even number of strings as parameters. The even numbered indices are keys and the odd indices are values. See the example for more information.

Creates a new Header.

Code:

/*
	Creates a header that looks like the following:

		login:scott
		passcode:tiger
		host:stompserver
		accept-version:1.1,1.2
*/
h := stomp.NewHeader(
    "login", "scott",
    "passcode", "tiger",
    "host", "stompserver",
    "accept-version", "1.1,1.2")
doSomethingWith(h)

func (*Header) Add

func (h *Header) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values associated with the key.

func (*Header) Clone

func (h *Header) Clone() *Header

Clone returns a deep copy of a Header.

func (*Header) Contains

func (h *Header) Contains(key string) (value string, ok bool)

Contains gets the first value associated with the given key, and also returns a bool indicating whether the header entry exists.

If there are no values associated with the key, Get returns "" for the value, and ok is false.

func (*Header) ContentLength

func (h *Header) ContentLength() (value int, ok bool, err error)

ContentLength returns the value of the "content-length" header entry. If the "content-length" header is missing, then ok is false. If the "content-length" entry is present but is not a valid non-negative integer then err is non-nil.

func (*Header) Del

func (h *Header) Del(key string)

Del deletes all header entries with the specified key.

func (*Header) Get

func (h *Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "".

func (*Header) GetAll

func (h *Header) GetAll(key string) []string

GetAll returns all of the values associated with a given key. Normally there is only one header entry per key, but it is permitted to have multiple entries according to the STOMP standard.

func (*Header) GetAt

func (h *Header) GetAt(index int) (key, value string)

Returns the header name and value at the specified index in the collection. The index should be in the range 0 <= index < Len(), a panic will occur if it is outside this range.

func (*Header) Len

func (h *Header) Len() int

Len returns the number of header entries in the header.

func (*Header) Set

func (h *Header) Set(key, value string)

Set replaces the value existing header entry with the specified key. If there is no existing header entry with the specified key, a new header entry is added.

type Message

type Message struct {
    // Indicates whether an error was received on the subscription.
    // The error will contain details of the error. If the server
    // sent an ERROR frame, then the Body, ContentType and Header fields
    // will be populated according to the contents of the ERROR frame.
    Err error

    // Destination the message is sent to. The STOMP server should
    // in turn send this message to a STOMP client that has subscribed
    // to the destination.
    Destination string

    // MIME content type.
    ContentType string // MIME content

    // Connection that the message was received on.
    Conn *Conn

    // Subscription associated with the message.
    Subscription *Subscription

    // Optional header entries. When received from the server,
    // these are the header entries received with the message.
    // When sending to the server, these are optional header entries
    // that accompany the message to its destination.
    *Header

    // The message body, which is an arbitrary sequence of bytes.
    // The ContentType indicates the format of this body.
    Body []byte // Content of message
}

A Message represents a message received from the STOMP server. In most cases a message corresponds to a single STOMP MESSAGE frame received from the STOMP server. If, however, the Err field is non-nil, then the message corresponds to a STOMP ERROR frame, or a connection error between the client and the server.

func (*Message) ShouldAck

func (msg *Message) ShouldAck() bool

ShouldAck returns true if this message should be acknowledged to the STOMP server that sent it.

type Options

type Options struct {
    // Login and passcode for authentication with the STOMP server.
    // If no authentication is required, leave blank.
    Login, Passcode string

    // Value for the "host" header entry when connecting to the
    // STOMP server. Leave blank for default value.
    Host string

    // Comma-separated list of acceptable STOMP versions.
    // Leave blank for default protocol negotiation, which is
    // the recommended setting.
    AcceptVersion string

    // Value to pass in the "heart-beat" header entry when connecting
    // to the STOMP server. Format is two non-negative integer values
    // separated by a comma. Leave blank for default heart-beat negotiation,
    // which is the recommended setting.
    HeartBeat string

    // As per the STOMP specification, we should expect some discrepancy
    // in incoming heartbeats. Add this time duration to the read timeout.
    // If this value is zero, it will be set to DefaultReadHeartBeatError.
    // If you really want to have zero error (eg for testing), set to a
    // negative value.
    ReadHeartBeatError time.Duration

    // Other header entries for STOMP servers that accept non-standard
    // header entries in the CONNECT frame.
    NonStandard *Header
}

Options for connecting to the STOMP server. Used with the stomp.Dial and stomp.Connect functions, both of which have examples.

type Reader

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

The Reader type reads STOMP frames from an underlying io.Reader. The reader is buffered, and the size of the buffer is the maximum size permitted for the STOMP frame command and header section. If a STOMP frame is rejected if its command and header section exceed the buffer size.

func NewReader

func NewReader(reader io.Reader) *Reader

NewReader creates a Reader with the default underlying buffer size.

func NewReaderSize

func NewReaderSize(reader io.Reader, bufferSize int) *Reader

NewReaderSize creates a Reader with an underlying bufferSize of the specified size.

func (*Reader) Read

func (r *Reader) Read() (*Frame, error)

Read a STOMP frame from the input. If the input contains one or more heart-beat characters and no frame, then nil will be returned for the frame. Calling programs should always check for a nil frame.

type Subscription

type Subscription struct {
    C chan *Message
    // contains filtered or unexported fields
}

The Subscription type represents a client subscription to a destination. The subscription is created by calling Conn.Subscribe.

Once a client has subscribed, it can receive messages from the C channel.

Code:

conn, err := stomp.Dial("tcp", "localhost:61613", stomp.Options{})
if err != nil {
    return err
}

sub, err := conn.Subscribe("/queue/test-2", stomp.AckClient)
if err != nil {
    return err
}

// receive 5 messages and then quit
for i := 0; i < 5; i++ {
    msg := <-sub.C
    if msg.Err != nil {
        return msg.Err
    }

    doSomethingWith(msg)

    // acknowledge the message
    err = conn.Ack(msg)
    if err != nil {
        return err
    }
}

err = sub.Unsubscribe()
if err != nil {
    return err
}

return conn.Disconnect()

func (*Subscription) AckMode

func (s *Subscription) AckMode() AckMode

AckMode returns the Acknowledgement mode specified when the subscription was created.

func (*Subscription) Active

func (s *Subscription) Active() bool

Active returns whether the subscription is still active. Returns false if the subscription has been unsubscribed.

func (*Subscription) Destination

func (s *Subscription) Destination() string

Destination for which the subscription applies.

func (*Subscription) Id

func (s *Subscription) Id() string

Identification for this subscription. Unique among all subscriptions for the same Client.

func (*Subscription) Read

func (s *Subscription) Read() (*Message, error)

Read a message from the subscription. This is a convenience method: many callers will prefer to read from the channel C directly.

func (*Subscription) Unsubscribe

func (s *Subscription) Unsubscribe() error

Unsubscribes and closes the channel C.

type Transaction

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

A Transaction applies to the sending of messages to the STOMP server, and the acknowledgement of messages received from the STOMP server. All messages sent and and acknowledged in the context of a transaction are processed atomically by the STOMP server.

Transactions are committed with the Commit method. When a transaction is committed, all sent messages, acknowledgements and negative acknowledgements, are processed by the STOMP server. Alternatively transactions can be aborted, in which case all sent messages, acknowledgements and negative acknowledgements are discarded by the STOMP server.

Code:

conn, err := stomp.Dial("tcp", "localhost:61613", stomp.Options{})
if err != nil {
    return err
}
defer conn.Disconnect()

sub, err := conn.Subscribe("/queue/test-2", stomp.AckClient)
if err != nil {
    return err
}

// receive 5 messages and then quit
for i := 0; i < 5; i++ {
    msg := <-sub.C
    if msg.Err != nil {
        return msg.Err
    }

    tx := conn.Begin()

    doAnotherThingWith(msg, tx)

    tx.Send("/queue/another-one", "text/plain",
        []byte(fmt.Sprintf("Message #%d", i)), nil)

    // acknowledge the message
    err = tx.Ack(msg)
    if err != nil {
        return err
    }

    err = tx.Commit()
    if err != nil {
        return err
    }
}

err = sub.Unsubscribe()
if err != nil {
    return err
}

return nil

func (*Transaction) Abort

func (tx *Transaction) Abort() error

Abort will abort the transaction. Any calls to Send, SendWithReceipt, Ack and Nack on this transaction will be discarded.

func (*Transaction) Ack

func (tx *Transaction) Ack(msg *Message) error

Ack sends an acknowledgement for the message to the server. The STOMP server will not process the acknowledgement until the transaction has been committed. If the subscription has an AckMode of AckAuto, calling this function has no effect.

func (*Transaction) Commit

func (tx *Transaction) Commit() error

Commit will commit the transaction. All messages and acknowledgements sent to the STOMP server on this transaction will be processed atomically.

func (*Transaction) Conn

func (tx *Transaction) Conn() *Conn

Conn returns the connection associated with this transaction.

func (*Transaction) Id

func (tx *Transaction) Id() string

Id returns the unique identifier for the transaction.

func (*Transaction) Nack

func (tx *Transaction) Nack(msg *Message) error

Nack sends a negative acknowledgement for the message to the server, indicating that this client cannot or will not process the message and that it should be processed elsewhere. The STOMP server will not process the negative acknowledgement until the transaction has been committed. It is an error to call this method if the subscription has an AckMode of AckAuto, because the STOMP server will not be expecting any kind of acknowledgement (positive or negative) for this message.

func (*Transaction) Send

func (tx *Transaction) Send(destination, contentType string, body []byte, userDefined *Header) error

Send sends a message to the STOMP server as part of a transaction. The server will not process the message until the transaction is committed. This method returns without confirming that the STOMP server has received the message. If the STOMP server does fail to receive the message for any reason, the connection will close.

The content type should be specified, according to the STOMP specification, but if contentType is an empty string, the message will be delivered without a content type header entry. The body array contains the message body, and its content should be consistent with the specified content type.

The message can contain optional, user-defined header entries in userDefined. If there are no optional header entries, then set userDefined to nil.

func (*Transaction) SendWithReceipt

func (tx *Transaction) SendWithReceipt(destination, contentType string, body []byte, userDefined *Header) error

Send sends a message to the STOMP server as part of a transaction. The server will not process the message until the transaction is committed. This method does not return until the STOMP server has confirmed receipt of the message.

The content type should be specified, according to the STOMP specification, but if contentType is an empty string, the message will be delivered without a content type header entry. The body array contains the message body, and its content should be consistent with the specified content type.

The message can contain optional, user-defined header entries in userDefined. If there are no optional header entries, then set userDefined to nil.

type Validator

type Validator interface {
    // Validate returns nil if the frame is valid, or an error if not valid.
    Validate(f *Frame) error
}

Validator is an interface for validating STOMP frames.

func NewValidator

func NewValidator(version Version) Validator

type Version

type Version string

Version is the STOMP protocol version.

const (
    V10 Version = "1.0"
    V11 Version = "1.1"
    V12 Version = "1.2"
)

func (Version) String

func (v Version) String() string

String returns a string representation of the STOMP version.

func (Version) SupportsNack

func (v Version) SupportsNack() bool

SupportsNack indicates whether this version of the STOMP protocol supports use of the NACK command.

type Writer

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

Writes STOMP frames to an underlying io.Writer.

func NewWriter

func NewWriter(writer io.Writer) *Writer

Creates a new Writer object, which writes to an underlying io.Writer.

func NewWriterSize

func NewWriterSize(writer io.Writer, bufferSize int) *Writer

func (*Writer) Write

func (w *Writer) Write(f *Frame) error

Write the contents of a frame to the underlying io.Writer.

Bugs

If the client does not read messages from the Subscription.C channel quickly enough, the client will stop reading messages from the server.

Directories

PathSynopsis
frameThe frame package contains constants associated with STOMP frames.
serverPackage server contains a simple STOMP server implementation.
server/clientPackage client implements client connectivity in the STOMP server.
server/queuePackage queue provides implementations of server-side queues.
server/topicPackage topic provides implementations of server-side topics.
stompdA simple, stand-alone STOMP server.
testutilPackage testutil contains operations useful for testing.

Package stomp imports 12 packages (graph) and is imported by 16 packages. Updated 2014-03-30. Refresh now. Tools for package owners.