stompserver

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: BSD-2-Clause Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package stompserver implements the in-process STOMP server used by the Fabric transport.

Index

Constants

View Source
const (
	HeaderXSessionID   = "X-Session-Id"
	HeaderConnection   = "Connection"
	HeaderUpgrade      = "Upgrade"
	HeaderUpgradeValue = "websocket"
	CookieNameSession  = "session"
)

HTTP Headers

View Source
const (
	LogBlockedIPAttempted  = "[ranch] blocked IP attempted connection: %s (reason: %s)"
	LogWebSocketConnection = "[ranch] websocket connection from: %s"
	LogWebSocketClosed     = "[ranch] websocket connection from: %s has been closed"
	LogWebSocketFailed     = "[ranch] failed websocket connection from: %s"
)

Log Messages

View Source
const (
	StatusMessageTooManyRequests = "Too many connection attempts. Please try again later."
)

HTTP Status Messages

Variables

This section is empty.

Functions

This section is empty.

Types

type ApplicationRequestHandlerFunction

type ApplicationRequestHandlerFunction func(destination string, message []byte, connectionId string)

ApplicationRequestHandlerFunction handles SEND frames targeting application destinations.

type AuthInfo added in v0.5.0

type AuthInfo struct {
	Username string
	Id       int
	Roles    []string
}

AuthInfo holds authentication details for the user.

func (*AuthInfo) HasRole added in v0.5.0

func (a *AuthInfo) HasRole(role string) bool

HasRole returns true if the user has the specified role.

type ConnEvent

type ConnEvent struct {
	ConnId string
	// contains filtered or unexported fields
}

ConnEvent carries STOMP connection event details.

type Connection added in v0.5.0

type Connection struct {
	Source string
}

Connection describes a raw connection lifecycle notification.

type FrameHandlerFunc added in v0.5.0

type FrameHandlerFunc func(conn StompConn, f *frame.Frame) error

FrameHandlerFunc is a function that processes a STOMP frame.

func ChainCommandMiddleware added in v0.5.0

func ChainCommandMiddleware(reg MiddlewareRegistry, command string, coreHandler FrameHandlerFunc) FrameHandlerFunc

ChainCommandMiddleware returns a FrameHandlerFunc that wraps the provided core handler with both global middleware (key "*") and command-specific middleware.

func ChainMiddleware added in v0.5.0

func ChainMiddleware(mws []MiddlewareFunc, final FrameHandlerFunc) FrameHandlerFunc

ChainMiddleware applies the list of middleware in order so that the first in the slice is the outermost middleware.

type HTTPHandlerRegistrar added in v0.9.0

type HTTPHandlerRegistrar interface {
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}

HTTPHandlerRegistrar is the subset of HTTP mux APIs needed to register a WebSocket endpoint.

type IPBlockingChecker added in v0.7.0

type IPBlockingChecker interface {
	IsIPBlocked(ip string) (bool, string) // returns blocked status and reason
	TrackConnection(ip string, sessionID string)
	TrackDisconnection(ip string, sessionID string)
	ExtractRealIP(remoteAddr string, headers map[string][]string) string
}

IPBlockingChecker is an interface for checking if an IP should be blocked

type MiddlewareFunc added in v0.5.0

type MiddlewareFunc func(FrameHandlerFunc) FrameHandlerFunc

MiddlewareFunc is a function that wraps a FrameHandlerFunc.

type MiddlewareRegistry added in v0.5.0

type MiddlewareRegistry map[string][]MiddlewareFunc

MiddlewareRegistry maps STOMP commands or "*" to middleware chains.

type RawConnResult added in v0.5.0

type RawConnResult struct {
	Conn RawConnection
	Err  error
}

RawConnResult carries an accepted raw connection or the accept error.

type RawConnection

type RawConnection interface {
	// ReadFrame Reads a single frame object
	ReadFrame() (*frame.Frame, error)
	// WriteFrame Sends a single frame object
	WriteFrame(frame *frame.Frame) error
	// SetReadDeadline Set deadline for reading frames
	SetReadDeadline(t time.Time)
	// GetRemoteAddr Returns the remote address of the connection
	GetRemoteAddr() string
	// Close the connection
	Close() error
}

RawConnection is the minimal frame-oriented connection needed by the STOMP server.

type RawConnectionListener

type RawConnectionListener interface {
	// Accept Blocks until a new RawConnection is established.
	Accept() (RawConnection, error)
	// Close Stops the connection listener.
	Close() error

	// GetConnectionOpenChannel will return a channel that emits connection results when clients connect.
	GetConnectionOpenChannel() chan *Connection

	// GetConnectionCloseChannel will return a channel the emits connection result when clients disconnect.
	GetConnectionCloseChannel() chan *Connection
}

RawConnectionListener accepts raw STOMP connections.

func NewTcpConnectionListener

func NewTcpConnectionListener(addr string) (RawConnectionListener, error)

NewTcpConnectionListener creates a TCP listener for raw STOMP connections.

func NewWebSocketConnectionFromExistingHttpServer

func NewWebSocketConnectionFromExistingHttpServer(httpServer *http.Server, handler HTTPHandlerRegistrar,
	endpoint string, allowedOrigins []string, logger *slog.Logger, debug bool, customSocketFunc http.HandlerFunc) (RawConnectionListener, error)

NewWebSocketConnectionFromExistingHttpServer registers a WebSocket STOMP endpoint on an existing HTTP server.

func NewWebSocketConnectionListener

func NewWebSocketConnectionListener(addr string, endpoint string, allowedOrigins []string, logger *slog.Logger, debug bool) (RawConnectionListener, error)

NewWebSocketConnectionListener creates an HTTP server that accepts WebSocket STOMP connections.

type StompConfig

type StompConfig interface {
	HeartBeat() int64
	AppDestinationPrefix() []string
	IsAppRequestDestination(destination string) bool
	Logger() *slog.Logger
	SetLogger(logger *slog.Logger)
	GetMiddlewareRegistry() MiddlewareRegistry
	SetMiddlewareRegistry(registry MiddlewareRegistry)
}

StompConfig exposes STOMP server configuration.

func NewStompConfig

func NewStompConfig(heartBeatMs int64, appDestinationPrefix []string) StompConfig

NewStompConfig creates STOMP server configuration with normalized application prefixes.

type StompConn

type StompConn interface {
	// Return unique connection Id string
	GetId() string
	// Return IP address of the connection
	GetIPAddress() string
	SendFrameToSubscription(f *frame.Frame, sub *Subscription)
	Close()
	GetSubscriptions() map[string]*Subscription
	AddSubscription(id string, destination string) (*Subscription, bool)
	RemoveSubscription(id string) (*Subscription, bool)
	GetEventsChannel() chan *ConnEvent
	SendError(err error)
	SendMessage(msg string)
}

StompConn is a server-side STOMP client connection.

func NewStompConn

func NewStompConn(rawConnection RawConnection, config StompConfig, events chan *ConnEvent) StompConn

NewStompConn creates and starts a server-side STOMP connection.

type StompServer

type StompServer interface {
	// starts the server
	Start()
	// stops the server
	Stop()
	// Ready is closed when the server is about to consume accepted connections.
	Ready() <-chan struct{}
	// sends a message to a given stomp topic destination
	SendMessage(destination string, messageBody []byte)
	// sends a message to a single connection client
	SendMessageToClient(connectionId string, destination string, messageBody []byte)
	// closes all connections from a specific IP address with a custom error message
	CloseConnectionsByIP(ip string, errorMessage string)
	// sets the IP blocking checker that gets called before allowing connections
	SetIPBlockingChecker(checker IPBlockingChecker)
	// registers a callback for stomp subscribe events
	OnSubscribeEvent(callback SubscribeHandlerFunction)
	// registers a callback for stomp unsubscribe events
	OnUnsubscribeEvent(callback UnsubscribeHandlerFunction)
	// registers a callback for application requests
	OnApplicationRequest(callback ApplicationRequestHandlerFunction)
	// SetConnectionEventCallback is used to set up a callback when certain STOMP session events happen
	// such as ConnectionStarting, ConnectionClosed, SubscribeToTopic, UnsubscribeFromTopic and IncomingMessage.
	SetConnectionEventCallback(connEventType StompSessionEventType, cb func(connEvent *ConnEvent))
}

StompServer accepts STOMP clients and routes frames to registered callbacks.

func NewStompServer

func NewStompServer(listener RawConnectionListener, config StompConfig) StompServer

NewStompServer creates a STOMP server around a raw connection listener.

type StompSessionEventType

type StompSessionEventType int

StompSessionEventType identifies a STOMP connection or subscription event.

const (
	// ConnectionStarting is emitted before a new connection starts processing.
	ConnectionStarting StompSessionEventType = iota
	// ConnectionEstablished is emitted after a connection is established.
	ConnectionEstablished
	// ConnectionClosed is emitted after a connection closes.
	ConnectionClosed
	// SubscribeToTopic is emitted after a client subscribes to a destination.
	SubscribeToTopic
	// UnsubscribeFromTopic is emitted after a client unsubscribes from a destination.
	UnsubscribeFromTopic
	// IncomingMessage is emitted when a client sends an application message.
	IncomingMessage
)

type SubscribeHandlerFunction

type SubscribeHandlerFunction func(conId string, subId string, destination string, frame *frame.Frame)

SubscribeHandlerFunction handles STOMP SUBSCRIBE frames.

type Subscription added in v0.5.0

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

Subscription represents a STOMP subscription owned by a connection.

type UnsubscribeHandlerFunction

type UnsubscribeHandlerFunction func(conId string, subId string, destination string)

UnsubscribeHandlerFunction handles STOMP UNSUBSCRIBE frames.

type WebSocketStompConnection added in v0.5.0

type WebSocketStompConnection struct {
	WSCon *websocket.Conn
	// contains filtered or unexported fields
}

WebSocketStompConnection adapts a WebSocket to the RawConnection interface.

func (*WebSocketStompConnection) Close added in v0.5.0

func (c *WebSocketStompConnection) Close() error

Close closes the underlying WebSocket.

func (*WebSocketStompConnection) GetRemoteAddr added in v0.6.0

func (c *WebSocketStompConnection) GetRemoteAddr() string

GetRemoteAddr returns the remote network address.

func (*WebSocketStompConnection) ReadFrame added in v0.5.0

func (c *WebSocketStompConnection) ReadFrame() (*frame.Frame, error)

ReadFrame reads a single STOMP frame from the WebSocket.

func (*WebSocketStompConnection) SetReadDeadline added in v0.5.0

func (c *WebSocketStompConnection) SetReadDeadline(t time.Time)

SetReadDeadline sets the read deadline on the underlying WebSocket.

func (*WebSocketStompConnection) WriteFrame added in v0.5.0

func (c *WebSocketStompConnection) WriteFrame(f *frame.Frame) error

WriteFrame writes a single STOMP frame to the WebSocket.

Jump to

Keyboard shortcuts

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