centrifuge

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 20 Imported by: 2 modules, 2 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.

README

GoDoc

Websocket client for Centrifugo server and Centrifuge library.

There is no v1 release of this library yet – API still evolves. At the moment patch version updates only contain backwards compatible changes, minor version updates can have backwards incompatible API changes.

Check out client SDK API specification to learn how this SDK behaves. It's recommended to read that before starting to work with this SDK as the spec covers common SDK behavior - describes client and subscription state transitions, main options and methods. Also check out examples folder.

The features implemented by this SDK can be found in SDK feature matrix.

The latest centrifuge-go is compatible with Centrifugo server v6, v5 and v4, and Centrifuge >= 0.25.0. For Centrifugo v2, Centrifugo v3 and Centrifuge < 0.25.0 you should use centrifuge-go v0.8.x.

Callbacks should not block

When using this SDK you should not block for a long time inside event handlers since handlers called synchronously by the SDK and block the connection read loop. The fact that the read loop is blocked also means that you can not issue blocking Client requests such as Publish, RPC, History, Presence, PresenceStats from the event handler code – this will result into a deadlock. Use a separate goroutine if you really need to issue a blocking call from inside an event handler.

I.e. this code is broken:

client.OnMessage(func(e centrifuge.MessageEvent) {
    result, err := c.RPC(context.Background(), "method", []byte("{}"))
    if err != nil {
        log.Println(err)
        return
    }
    // Will never be called.
    log.Printf("RPC result: %s", string(result.Data))
})

This code is correct as it does not block event handler forever:

client.OnMessage(func(e centrifuge.MessageEvent) {
    // When issue blocking requests from inside event handler we must use
    // a goroutine. Otherwise, we will ge a deadlock since the connection
    // read loop is blocked.
    go func() {
        result, err := c.RPC(context.Background(), "method", []byte("{}"))
        if err != nil {
            log.Println(err)
            return
        }
        log.Printf("RPC result: %s", string(result.Data))
    }()
})

You can find similar limitations in eclipse/paho.mqtt.golang. In short, this is caused by a challenging mix of asynchronous protocol, Go and callback approach. In the previous versions of this SDK we allowed blocking requests from within event handlers – but it contradicts with the real-time nature of Centrifugal ecosystem, because we had to use separate callback queue, and that queue could grow huge without a reasonable way to backpressure (which we were not able to find).

If you are calling Publish, RPC, History, Presence, PresenceStats from the outside of event handler – you should not do any special care. Also, if you are calling your own blocking APIs from inside Centrifuge event handlers – you won't get the deadlock, but the read loop of the underlying connection will not proceed till the event handler returns.

Run tests

First run Centrifugo instance:

docker run -it --rm -p 8000:8000 \
-e CENTRIFUGO_CHANNEL_WITHOUT_NAMESPACE_DELTA_PUBLISH=true \
-e CENTRIFUGO_CHANNEL_WITHOUT_NAMESPACE_ALLOWED_DELTA_TYPES="fossil" \
-e CENTRIFUGO_CHANNEL_WITHOUT_NAMESPACE_HISTORY_SIZE="100" \
-e CENTRIFUGO_CHANNEL_WITHOUT_NAMESPACE_HISTORY_TTL="300s" \
-e CENTRIFUGO_CHANNEL_WITHOUT_NAMESPACE_FORCE_RECOVERY="true" \
centrifugo/centrifugo:v6 centrifugo --client.insecure

Then run go test

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTimeout returned if operation timed out.
	ErrTimeout = errors.New("timeout")
	// ErrClientDisconnected can be returned if client goes to
	// disconnected state while operation in progress.
	ErrClientDisconnected = errors.New("client disconnected")
	// ErrClientClosed can be returned if client is closed.
	ErrClientClosed = errors.New("client closed")
	// ErrSubscriptionUnsubscribed returned if Subscription is unsubscribed.
	ErrSubscriptionUnsubscribed = errors.New("subscription unsubscribed")
	// ErrDuplicateSubscription returned if subscription to the same channel
	// already registered in current client instance. This is due to the fact
	// that server does not allow subscribing to the same channel twice for
	// the same connection.
	ErrDuplicateSubscription = errors.New("duplicate subscription")
	// ErrUnauthorized is a special error which may be returned by application
	// from GetToken function to indicate lack of operation permission.
	ErrUnauthorized = errors.New("unauthorized")
)

Functions

This section is empty.

Types

type Client

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

Client represents client connection to Centrifugo or Centrifuge library based server. It provides methods to set various event handlers, subscribe channels, call RPC commands etc. Call client Connect method to trigger actual connection with a server. Call client Close method to clean up state when you don't need client instance anymore.

func NewJsonClient

func NewJsonClient(endpoint string, config Config) *Client

NewJsonClient initializes Client which uses JSON-based protocol internally. After client initialized call Client.Connect method. Use Client.NewSubscription to create Subscription objects. The provided endpoint must be a valid URL with ws:// or wss:// scheme – otherwise NewJsonClient will panic.

func NewProtobufClient

func NewProtobufClient(endpoint string, config Config) *Client

NewProtobufClient initializes Client which uses Protobuf-based protocol internally. After client initialized call Client.Connect method. Use Client.NewSubscription to create Subscription objects. The provided endpoint must be a valid URL with ws:// or wss:// scheme – otherwise NewProtobufClient will panic.

func (*Client) Close

func (c *Client) Close()

Close closes Client and cleanups resources. Client is unusable after this. Use this method if you don't need client anymore, otherwise look at Client.Disconnect.

func (*Client) Connect

func (c *Client) Connect() error

Connect dials to server and sends connect message. Will return an error if first dial with a server failed. In case of failure client will automatically reconnect. To temporary disconnect from a server call Client.Disconnect.

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect client from server. It's still possible to connect again later. If you don't need Client anymore – use Client.Close.

func (*Client) GetSubscription

func (c *Client) GetSubscription(channel string) (*Subscription, bool)

GetSubscription allows getting Subscription from the internal client registry.

func (*Client) History

func (c *Client) History(ctx context.Context, channel string, opts ...HistoryOption) (HistoryResult, error)

History for a channel without being subscribed.

func (*Client) NewSubscription

func (c *Client) NewSubscription(channel string, config ...SubscriptionConfig) (*Subscription, error)

NewSubscription allocates new Subscription on a channel. As soon as Subscription successfully created Client keeps reference to it inside internal map registry to manage automatic resubscribe on reconnect. After creating Subscription call its Subscription.Subscribe method to actually start subscribing process. To temporarily unsubscribe call Subscription.Unsubscribe. If you finished with Subscription then you can remove it from the internal registry by calling Client.RemoveSubscription method.

func (*Client) OnConnected

func (c *Client) OnConnected(handler ConnectedHandler)

OnConnected is a function to handle connect event.

func (*Client) OnConnecting

func (c *Client) OnConnecting(handler ConnectingHandler)

OnConnecting is a function to handle connecting event.

func (*Client) OnDisconnected

func (c *Client) OnDisconnected(handler DisconnectHandler)

OnDisconnected is a function to handle moveToDisconnected event.

func (*Client) OnError

func (c *Client) OnError(handler ErrorHandler)

OnError is a function that will receive unhandled errors for logging.

func (*Client) OnJoin

func (c *Client) OnJoin(handler ServerJoinHandler)

OnJoin sets function to handle Join event from server-side subscriptions.

func (*Client) OnLeave

func (c *Client) OnLeave(handler ServerLeaveHandler)

OnLeave sets function to handle Leave event from server-side subscriptions.

func (*Client) OnMessage

func (c *Client) OnMessage(handler MessageHandler)

OnMessage allows processing async message from server to client.

func (*Client) OnPublication

func (c *Client) OnPublication(handler ServerPublicationHandler)

OnPublication sets function to handle Publications from server-side subscriptions.

func (*Client) OnSubscribed

func (c *Client) OnSubscribed(handler ServerSubscribedHandler)

OnSubscribed sets function to handle server-side subscription subscribe events.

func (*Client) OnSubscribing

func (c *Client) OnSubscribing(handler ServerSubscribingHandler)

OnSubscribing sets function to handle server-side subscription subscribing events.

func (*Client) OnUnsubscribed

func (c *Client) OnUnsubscribed(handler ServerUnsubscribedHandler)

OnUnsubscribed sets function to handle unsubscribe from server-side subscriptions.

func (*Client) Presence

func (c *Client) Presence(ctx context.Context, channel string) (PresenceResult, error)

Presence for a channel without being subscribed.

func (*Client) PresenceStats

func (c *Client) PresenceStats(ctx context.Context, channel string) (PresenceStatsResult, error)

PresenceStats for a channel without being subscribed.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, channel string, data []byte) (PublishResult, error)

Publish data into channel.

func (*Client) RPC

func (c *Client) RPC(ctx context.Context, method string, data []byte) (RPCResult, error)

RPC allows sending data to a server and waiting for a response. RPC handler must be registered on server.

func (*Client) RemoveSubscription

func (c *Client) RemoveSubscription(sub *Subscription) error

RemoveSubscription removes Subscription from the internal client registry. Make sure Subscription is in unsubscribed state before removing it.

func (*Client) Send

func (c *Client) Send(ctx context.Context, data []byte) error

Send message to server without waiting for response. Message handler must be registered on server.

func (*Client) SetToken

func (c *Client) SetToken(token string)

SetToken allows updating Client's connection token.

func (*Client) State

func (c *Client) State() State

State returns current Client state. Note that while you are processing this state - Client can move to a new one.

func (*Client) Subscriptions

func (c *Client) Subscriptions() map[string]*Subscription

Subscriptions returns a map with all currently registered client-side subscriptions.

type ClientInfo

type ClientInfo struct {
	// Client is a client unique id.
	Client string
	// User is an ID of authenticated user. Zero value means anonymous user.
	User string
	// ConnInfo is additional information about connection.
	ConnInfo []byte
	// ChanInfo is additional information about connection in context of
	// channel subscription.
	ChanInfo []byte
}

ClientInfo contains information about client connection.

type Config

type Config struct {
	// Token for a connection authentication.
	Token string
	// GetToken called by SDK to get or refresh connection token.
	GetToken func(ConnectionTokenEvent) (string, error)
	// Data is an arbitrary data which can be sent to a server in a Connect command.
	// Make sure it's a valid JSON when using JSON protocol client.
	Data []byte
	// CookieJar specifies the cookie jar to send in WebSocket Upgrade request.
	CookieJar http.CookieJar
	// Header specifies custom HTTP Header to send in WebSocket Upgrade request.
	Header http.Header
	// Name allows setting client name. You should only use a limited
	// amount of client names throughout your applications – i.e. don't
	// make it unique per user for example, this name semantically represents
	// an environment from which client connects.
	// Zero value means "go".
	Name string
	// Version allows setting client version. This is an application
	// specific information. By default, no version set.
	Version string
	// Proxy specifies a function to return a proxy for a given Request.
	// If the function returns a non-nil error, the request is aborted with the
	// provided error. If function returns a nil *URL, no proxy is used.
	// If Proxy is nil then http.ProxyFromEnvironment will be used.
	Proxy func(*http.Request) (*url.URL, error)
	// NetDialContext specifies the dial function for creating TCP connections. If
	// NetDialContext is nil, net.DialContext is used.
	NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
	// ReadTimeout is how long to wait read operations to complete.
	// Zero value means 5 * time.Second.
	ReadTimeout time.Duration
	// WriteTimeout is Websocket write timeout.
	// Zero value means 1 * time.Second.
	WriteTimeout time.Duration
	// HandshakeTimeout specifies the duration for the handshake to complete.
	// Zero value means 1 * time.Second.
	HandshakeTimeout time.Duration
	// MaxServerPingDelay used to set maximum delay of ping from server.
	// Zero value means 10 * time.Second.
	MaxServerPingDelay time.Duration
	// MinReconnectDelay is the minimum delay between reconnection attempts.
	// This delay is jittered.
	// Zero value means 200 * time.Millisecond.
	MinReconnectDelay time.Duration
	// MaxReconnectDelay is the maximum delay between reconnection attempts.
	// Zero value means 20 * time.Second.
	MaxReconnectDelay time.Duration
	// TLSConfig specifies the TLS configuration to use with tls.Client.
	// If nil, the default configuration is used.
	TLSConfig *tls.Config
	// EnableCompression specifies if the client should attempt to negotiate
	// per message compression (RFC 7692). Setting this value to true does not
	// guarantee that compression will be supported. Currently, only "no context
	// takeover" modes are supported.
	EnableCompression bool
	// LogLevel to use, by default no logs will be exposed by centrifuge-go. Most of the
	// time available protocol callbacks cover all necessary information about client-server
	// communication.
	LogLevel LogLevel
	// LogHandler is a function that will be called for each log entry. Log entries
	// are sent asynchronously and from a separate goroutine by centrifuge-go with an
	// intermediary channel buffer (fixed capacity 256). If your LogHandler is not
	// processing log entries fast enough, centrifuge-go will drop log entries.
	LogHandler func(LogEntry)
}

Config contains various client options.

type ConfigurationError

type ConfigurationError struct {
	Err error
}

func (ConfigurationError) Error

func (c ConfigurationError) Error() string

func (ConfigurationError) Unwrap

func (c ConfigurationError) Unwrap() error

type ConnectError

type ConnectError struct {
	Err error
}

func (ConnectError) Error

func (c ConnectError) Error() string

func (ConnectError) Unwrap

func (c ConnectError) Unwrap() error

type ConnectedEvent

type ConnectedEvent struct {
	ClientID string
	Version  string
	Data     []byte
}

ConnectedEvent is a connected event context passed to OnConnected callback.

type ConnectedHandler

type ConnectedHandler func(ConnectedEvent)

ConnectedHandler is an interface describing how to handle connect event.

type ConnectingEvent

type ConnectingEvent struct {
	Code   uint32
	Reason string
}

ConnectingEvent is a connecting event context passed to OnConnecting callback.

type ConnectingHandler

type ConnectingHandler func(ConnectingEvent)

ConnectingHandler is an interface describing how to handle connecting event.

type ConnectionTokenEvent

type ConnectionTokenEvent struct {
}

ConnectionTokenEvent may contain some useful contextual information in the future. For now, it's empty.

type DeltaType

type DeltaType string

DeltaType represents type of delta used for Subscription.

const (
	// DeltaTypeNone means that no delta is used for this subscription.
	DeltaTypeNone DeltaType = ""
	// DeltaTypeFossil means Fossil-based delta.
	DeltaTypeFossil DeltaType = "fossil"
)

type DisconnectHandler

type DisconnectHandler func(DisconnectedEvent)

DisconnectHandler is an interface describing how to handle moveToDisconnected event.

type DisconnectedEvent

type DisconnectedEvent struct {
	Code   uint32
	Reason string
}

DisconnectedEvent is a disconnected event context passed to OnDisconnected callback.

type Error

type Error struct {
	Code      uint32
	Message   string
	Temporary bool
}

Error represents protocol-level error.

func (Error) Error

func (e Error) Error() string

type ErrorEvent

type ErrorEvent struct {
	Error error
}

ErrorEvent is an error event context passed to OnError callback.

type ErrorHandler

type ErrorHandler func(ErrorEvent)

ErrorHandler is an interface describing how to handle error event.

type HistoryOption

type HistoryOption func(options *HistoryOptions)

func WithHistoryLimit

func WithHistoryLimit(limit int32) HistoryOption

func WithHistoryReverse

func WithHistoryReverse(reverse bool) HistoryOption

func WithHistorySince

func WithHistorySince(sp *StreamPosition) HistoryOption

type HistoryOptions

type HistoryOptions struct {
	Limit   int32
	Since   *StreamPosition
	Reverse bool
}

type HistoryResult

type HistoryResult struct {
	Publications []Publication
	Offset       uint64
	Epoch        string
}

HistoryResult contains the result of history op.

type JoinEvent

type JoinEvent struct {
	ClientInfo
}

JoinEvent has info about user who joined channel.

type JoinHandler

type JoinHandler func(JoinEvent)

JoinHandler is a function to handle join messages.

type LeaveEvent

type LeaveEvent struct {
	ClientInfo
}

LeaveEvent has info about user who left channel.

type LeaveHandler

type LeaveHandler func(LeaveEvent)

LeaveHandler is a function to handle leave messages.

type LogEntry

type LogEntry struct {
	Level   LogLevel
	Message string
	Fields  map[string]string
}

LogEntry describes a log entry.

type LogHandler

type LogHandler func(LogEntry)

LogHandler handles log entries - i.e. writes into correct destination if necessary.

type LogLevel

type LogLevel int

LogLevel describes the chosen log level.

const (
	// LogLevelNone means no logging.
	LogLevelNone LogLevel = iota
	// LogLevelTrace turns on trace logs - should only be used during development. This
	// log level shows all client-server communication (including token content) and
	// affects performance significantly.
	LogLevelTrace
	// LogLevelDebug turns on debug logs - it's generally too much for production in normal
	// conditions but can help when developing and investigating problems in production.
	LogLevelDebug
)

func (LogLevel) String

func (l LogLevel) String() string

type MessageEvent

type MessageEvent struct {
	Data []byte
}

MessageEvent is an event for async message from server to client.

type MessageHandler

type MessageHandler func(MessageEvent)

MessageHandler is an interface describing how to handle async message from server.

type PresenceResult

type PresenceResult struct {
	Clients map[string]ClientInfo
}

PresenceResult contains the result of presence op.

type PresenceStats

type PresenceStats struct {
	NumClients int
	NumUsers   int
}

PresenceStats represents short presence information.

type PresenceStatsResult

type PresenceStatsResult struct {
	PresenceStats
}

PresenceStatsResult wraps presence stats.

type Publication

type Publication struct {
	// Offset is an incremental position number inside history stream.
	// Zero value means that channel does not maintain Publication stream.
	Offset uint64
	// Data published to channel.
	Data []byte
	// Info is optional information about client connection published
	// this data to channel.
	Info *ClientInfo
	// Tags contain custom key-value pairs attached to Publication.
	Tags map[string]string
}

Publication is a data sent to channel.

type PublicationEvent

type PublicationEvent struct {
	Publication
}

PublicationEvent has info about received channel Publication.

type PublicationHandler

type PublicationHandler func(PublicationEvent)

PublicationHandler is a function to handle messages published in channels.

type PublishResult

type PublishResult struct{}

PublishResult contains the result of publish.

type RPCResult

type RPCResult struct {
	Data []byte
}

RPCResult contains data returned from server as RPC result.

type RefreshError

type RefreshError struct {
	Err error
}

func (RefreshError) Error

func (r RefreshError) Error() string

func (RefreshError) Unwrap

func (r RefreshError) Unwrap() error

type ServerJoinEvent

type ServerJoinEvent struct {
	Channel string
	ClientInfo
}

ServerJoinEvent has info about user who left channel.

type ServerJoinHandler

type ServerJoinHandler func(ServerJoinEvent)

ServerJoinHandler is an interface describing how to handle Join events from server-side subscriptions.

type ServerLeaveEvent

type ServerLeaveEvent struct {
	Channel string
	ClientInfo
}

ServerLeaveEvent has info about user who joined channel.

type ServerLeaveHandler

type ServerLeaveHandler func(ServerLeaveEvent)

ServerLeaveHandler is an interface describing how to handle Leave events from server-side subscriptions.

type ServerPublicationEvent

type ServerPublicationEvent struct {
	Channel string
	Publication
}

ServerPublicationEvent has info about received channel Publication.

type ServerPublicationHandler

type ServerPublicationHandler func(ServerPublicationEvent)

ServerPublicationHandler is an interface describing how to handle Publication from server-side subscriptions.

type ServerSubscribedEvent

type ServerSubscribedEvent struct {
	Channel        string
	WasRecovering  bool
	Recovered      bool
	Recoverable    bool
	Positioned     bool
	StreamPosition *StreamPosition
	Data           []byte
}

type ServerSubscribedHandler

type ServerSubscribedHandler func(ServerSubscribedEvent)

ServerSubscribedHandler is an interface describing how to handle subscribe events from server-side subscriptions.

type ServerSubscribingEvent

type ServerSubscribingEvent struct {
	Channel string
}

ServerSubscribingEvent is an event passed to subscribing event handler.

type ServerSubscribingHandler

type ServerSubscribingHandler func(ServerSubscribingEvent)

ServerSubscribingHandler is an interface describing how to handle subscribing events for server-side subscriptions.

type ServerUnsubscribedEvent

type ServerUnsubscribedEvent struct {
	Channel string
}

ServerUnsubscribedEvent is an event passed to unsubscribe event handler.

type ServerUnsubscribedHandler

type ServerUnsubscribedHandler func(ServerUnsubscribedEvent)

ServerUnsubscribedHandler is an interface describing how to handle unsubscribe events from server-side subscriptions.

type State

type State string

State of client connection.

const (
	StateDisconnected State = "disconnected"
	StateConnecting   State = "connecting"
	StateConnected    State = "connected"
	StateClosed       State = "closed"
)

Describe client connection states.

type StreamPosition

type StreamPosition struct {
	Offset uint64
	Epoch  string
}

type SubState

type SubState string

SubState represents state of Subscription.

const (
	SubStateUnsubscribed SubState = "unsubscribed"
	SubStateSubscribing  SubState = "subscribing"
	SubStateSubscribed   SubState = "subscribed"
)

Different states of Subscription.

type SubscribedEvent

type SubscribedEvent struct {
	Positioned     bool
	Recoverable    bool
	StreamPosition *StreamPosition
	WasRecovering  bool
	Recovered      bool
	Data           []byte
}

SubscribedEvent is an event context passed to subscribe success callback.

type SubscribedHandler

type SubscribedHandler func(SubscribedEvent)

SubscribedHandler is a function to handle subscribe success event.

type SubscribingEvent

type SubscribingEvent struct {
	Code   uint32
	Reason string
}

SubscribingEvent is an event passed to subscribing event handler.

type SubscribingHandler

type SubscribingHandler func(SubscribingEvent)

SubscribingHandler is a function to handle subscribe success event.

type Subscription

type Subscription struct {

	// Channel for a subscription.
	Channel string
	// contains filtered or unexported fields
}

Subscription represents client subscription to channel. DO NOT initialize this struct directly, instead use Client.NewSubscription method to create channel subscriptions.

func (*Subscription) History

func (s *Subscription) History(ctx context.Context, opts ...HistoryOption) (HistoryResult, error)

History allows extracting channel history. By default, it returns current stream top position without publications. Use WithHistoryLimit with a value > 0 to make this func to return publications.

func (*Subscription) OnError

func (s *Subscription) OnError(handler SubscriptionErrorHandler)

OnError allows setting SubscriptionErrorHandler to SubEventHandler.

func (*Subscription) OnJoin

func (s *Subscription) OnJoin(handler JoinHandler)

OnJoin allows setting JoinHandler to SubEventHandler.

func (*Subscription) OnLeave

func (s *Subscription) OnLeave(handler LeaveHandler)

OnLeave allows setting LeaveHandler to SubEventHandler.

func (*Subscription) OnPublication

func (s *Subscription) OnPublication(handler PublicationHandler)

OnPublication allows setting PublicationHandler to SubEventHandler.

func (*Subscription) OnSubscribed

func (s *Subscription) OnSubscribed(handler SubscribedHandler)

OnSubscribed allows setting SubscribedHandler to SubEventHandler.

func (*Subscription) OnSubscribing

func (s *Subscription) OnSubscribing(handler SubscribingHandler)

OnSubscribing allows setting SubscribingHandler to SubEventHandler.

func (*Subscription) OnUnsubscribed

func (s *Subscription) OnUnsubscribed(handler UnsubscribedHandler)

OnUnsubscribed allows setting UnsubscribedHandler to SubEventHandler.

func (*Subscription) Presence

func (s *Subscription) Presence(ctx context.Context) (PresenceResult, error)

Presence allows extracting channel presence.

func (*Subscription) PresenceStats

func (s *Subscription) PresenceStats(ctx context.Context) (PresenceStatsResult, error)

PresenceStats allows extracting channel presence stats.

func (*Subscription) Publish

func (s *Subscription) Publish(ctx context.Context, data []byte) (PublishResult, error)

Publish allows publishing data to the subscription channel.

func (*Subscription) State

func (s *Subscription) State() SubState

func (*Subscription) Subscribe

func (s *Subscription) Subscribe() error

Subscribe allows initiating subscription process.

func (*Subscription) Unsubscribe

func (s *Subscription) Unsubscribe() error

Unsubscribe allows unsubscribing from channel.

type SubscriptionConfig

type SubscriptionConfig struct {
	// Data is an arbitrary data to pass to a server in each subscribe request.
	Data []byte
	// Token for Subscription.
	Token string
	// GetToken called to get or refresh private channel subscription token.
	GetToken func(SubscriptionTokenEvent) (string, error)
	// Positioned flag asks server to make Subscription positioned. Only makes sense
	// in channels with history stream on.
	Positioned bool
	// Recoverable flag asks server to make Subscription recoverable. Only makes sense
	// in channels with history stream on.
	Recoverable bool
	// JoinLeave flag asks server to push join/leave messages.
	JoinLeave bool
	// Delta allows to specify delta type for the subscription. By default, no delta is used.
	Delta DeltaType
	// Filter expression for subscription.
	Filter string
	// MinResubscribeDelay is the minimum delay between resubscription attempts.
	// This delay is jittered.
	// Zero value means 200 * time.Millisecond.
	MinResubscribeDelay time.Duration
	// MaxResubscribeDelay is the maximum delay between resubscription attempts.
	// Zero value means 20 * time.Second.
	MaxResubscribeDelay time.Duration
}

SubscriptionConfig allows setting Subscription options.

type SubscriptionErrorEvent

type SubscriptionErrorEvent struct {
	Error error
}

SubscriptionErrorEvent is a subscribe error event context passed to event callback.

type SubscriptionErrorHandler

type SubscriptionErrorHandler func(SubscriptionErrorEvent)

SubscriptionErrorHandler is a function to handle subscribe error event.

type SubscriptionRefreshError

type SubscriptionRefreshError struct {
	Err error
}

func (SubscriptionRefreshError) Error

func (s SubscriptionRefreshError) Error() string

func (SubscriptionRefreshError) Unwrap

func (s SubscriptionRefreshError) Unwrap() error

type SubscriptionSubscribeError

type SubscriptionSubscribeError struct {
	Err error
}

func (SubscriptionSubscribeError) Error

func (SubscriptionSubscribeError) Unwrap

func (s SubscriptionSubscribeError) Unwrap() error

type SubscriptionTokenEvent

type SubscriptionTokenEvent struct {
	Channel string
}

SubscriptionTokenEvent contains info required to get subscription token when client wants to subscribe on private channel.

type TransportError

type TransportError struct {
	Err error
}

func (TransportError) Error

func (t TransportError) Error() string

func (TransportError) Unwrap

func (t TransportError) Unwrap() error

type UnsubscribeResult

type UnsubscribeResult struct{}

type UnsubscribedEvent

type UnsubscribedEvent struct {
	Code   uint32
	Reason string
}

UnsubscribedEvent is an event passed to unsubscribe event handler.

type UnsubscribedHandler

type UnsubscribedHandler func(UnsubscribedEvent)

UnsubscribedHandler is a function to handle unsubscribe event.

Jump to

Keyboard shortcuts

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