Help us shape the future of Go! Take the 2026 Go Developer Survey

publisher

package
v1.75.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 7 Imported by: 0

README

Package publisher

Пакет publisher предоставляет удобный механизм отправки сообщений через STOMP-протокол с поддержкой middleware и повторного подключения.

Types

Publisher

Структура Publisher инкапсулирует логику подключения к STOMP-брокеру и отправки сообщений с возможностью настройки middleware и опций соединения.

Methods:

NewPublisher(address string, queue string, opts ...Option) *Publisher

Создаёт новый экземпляр Publisher с заданным адресом брокера, очередью и опциями.

(p *Publisher) Publish(ctx context.Context, msg *Message) error

Публикует сообщение в очередь, указанную при создании.

(p *Publisher) PublishTo(ctx context.Context, queue string, msg *Message) error

Публикует сообщение в указанную очередь.

(p *Publisher) Close() error

Закрывает текущее STOMP-соединение.

(p *Publisher) Healthcheck(ctx context.Context) error

Проверить работоспособность соединения паблишера. Возвращает ошибку при проблемах с подключением.

Message

Структура Message представляет сообщение для публикации.

Methods:

Json(body []byte) *Message

Создаёт сообщение с типом application/json.

PlainText(body []byte) *Message

Создаёт сообщение с типом plain/text.

(m *Message) WithHeader(key string, value string) *Message

Добавляет заголовок к сообщению.

Option

Функция, применяющая опции к Publisher.

Functions:

WithMiddlewares(mws ...Middleware) Option

Добавляет middleware в цепочку обработки публикации.

WithConnectionOptions(connOpts ...consumer.ConnOption) Option

Передаёт опции соединения для подключения к STOMP-брокеру.

Middleware

Функция, принимающая RoundTripper и возвращающая новый RoundTripper. Позволяет оборачивать логику публикации.

RoundTripper

Интерфейс, реализующий отправку сообщения.

RoundTripperFunc

Функциональный адаптер, реализующий интерфейс RoundTripper.

Methods:

(f RoundTripperFunc) Publish(ctx context.Context, queue string, msg *Message) error

Вызывает саму функцию.

PublishOption

Тип PublishOption представляет собой функцию, применяющую изменения к STOMP-фрейму. Полностью совместим с опциями github.com/go-stomp/stomp/v3/frame.

Usage

Basic publisher usage
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/stompx/publisher"
)

func main() {
	// Создание нового паблишера
	pub := publisher.NewPublisher("localhost:61613", "/queue/example")

	// Подготовка сообщения
	msg := publisher.Json([]byte(`{"event":"user_created"}`)).
		WithHeader("X-Custom-Header", "value")

	// Публикация сообщения
	err := pub.Publish(context.Background(), msg)
	if err != nil {
		log.Fatalf("publish error: %v", err)
	}

	// Завершение соединения
	err = pub.Close()
	if err != nil {
		log.Fatalf("close error: %v", err)
	}
}
With middlewares and connection options
import (
	"github.com/go-stomp/stomp/v3"
	"github.com/txix-open/isp-kit/stompx/publisher"
)

pub := publisher.NewPublisher(
	"localhost:61613",
	"/queue/another",
	publisher.WithConnectionOptions(stomp.ConnOpt.Login("user", "pass")),
	publisher.WithMiddlewares(
		func(next publisher.RoundTripper) publisher.RoundTripper {
			return publisher.RoundTripperFunc(func(ctx context.Context, queue string, msg *publisher.Message) error {
				// логика до
				err := next.Publish(ctx, queue, msg)
				// логика после
				return err
			})
		},
	),
)

Documentation

Overview

Package publisher provides functionality for publishing messages to a STOMP broker.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Message

type Message struct {
	// ContentType is the MIME type of the message body.
	ContentType string
	// Body is the raw message content.
	Body []byte
	// Opts are publication options (headers, etc.).
	Opts []PublishOption
}

Message represents a message to be published to a STOMP broker.

func Json

func Json(body []byte) *Message

Json creates a new message with JSON content type.

func PlainText

func PlainText(body []byte) *Message

PlainText creates a new message with plain text content type.

func (*Message) WithHeader

func (m *Message) WithHeader(key string, value string) *Message

WithHeader adds a header to the message.

type Middleware

type Middleware func(next RoundTripper) RoundTripper

Middleware is a function that wraps a RoundTripper with additional functionality.

type Option

type Option func(p *Publisher)

Option is a function that applies configuration options to a Publisher.

func WithConnectionOptions

func WithConnectionOptions(connOpts ...consumer.ConnOption) Option

WithConnectionOptions adds connection options to the publisher.

func WithMiddlewares

func WithMiddlewares(mws ...Middleware) Option

WithMiddlewares adds middleware functions to the publisher.

type PublishOption

type PublishOption = func(*frame.Frame) error

PublishOption is a function type for configuring message publication.

type Publisher

type Publisher struct {
	// Address is the broker address.
	Address string
	// Queue is the default queue name to publish to.
	Queue string
	// ConnOpts are connection options.
	ConnOpts []consumer.ConnOption
	// Middlewares are middleware functions applied to the round tripper.
	Middlewares []Middleware
	// contains filtered or unexported fields
}

Publisher manages a connection to a STOMP broker for publishing messages.

func NewPublisher

func NewPublisher(address string, queue string, opts ...Option) *Publisher

NewPublisher creates a new Publisher with the provided configuration options.

func (*Publisher) Close added in v1.32.0

func (p *Publisher) Close() error

Close disconnects the publisher from the broker.

func (*Publisher) Healthcheck added in v1.58.0

func (p *Publisher) Healthcheck(ctx context.Context) error

Healthcheck verifies that the publisher can connect to the broker.

func (*Publisher) Publish

func (p *Publisher) Publish(ctx context.Context, msg *Message) error

Publish sends a message to the default queue configured for this publisher.

func (*Publisher) PublishTo

func (p *Publisher) PublishTo(ctx context.Context, queue string, msg *Message) error

PublishTo sends a message to the specified queue.

type RoundTripper

type RoundTripper interface {
	Publish(ctx context.Context, queue string, msg *Message) error
}

RoundTripper defines the interface for publishing messages.

type RoundTripperFunc

type RoundTripperFunc func(ctx context.Context, queue string, msg *Message) error

RoundTripperFunc is an adapter type that allows using functions as round trippers.

func (RoundTripperFunc) Publish

func (f RoundTripperFunc) Publish(ctx context.Context, queue string, msg *Message) error

Publish calls the underlying function.

Jump to

Keyboard shortcuts

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