gocent

package module
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2022 License: MIT Imports: 9 Imported by: 6

README

Gocent

Gocent is a Go HTTP API client for Centrifugo real-time messaging server.

Documentation

Installation

Install Gocent using the "go get" command:

go get github.com/centrifugal/gocent/v3

License

Gocent is available under the MIT license.

Documentation

Overview

Package gocent is a Go language client for Centrifugo real-time messaging server HTTP API.

Index

Constants

View Source
const NoLimit = -1

NoLimit defines that limit should not be applied.

Variables

View Source
var (
	// ErrMalformedResponse can be returned when server replied with invalid response.
	ErrMalformedResponse = errors.New("malformed response returned from server")
	// ErrPipeEmpty returned when no commands found in Pipe.
	ErrPipeEmpty = errors.New("no commands in pipe")
)
View Source
var DefaultHTTPClient = &http.Client{Transport: &http.Transport{
	MaxIdleConnsPerHost: 100,
}, Timeout: time.Second}

DefaultHTTPClient will be used by default for HTTP requests.

Functions

This section is empty.

Types

type BroadcastResult

type BroadcastResult struct {
	Responses []PublishResponse `json:"responses"`
}

BroadcastResult is a result of broadcast command.

type ChannelInfo

type ChannelInfo struct {
	NumUsers int32 `json:"num_users"`
}

type ChannelsOption

type ChannelsOption func(options *ChannelsOptions)

ChannelsOption is a type to represent various Channels call options.

func WithPattern

func WithPattern(pattern string) ChannelsOption

WithLimit allows to set HistoryOptions.Limit.

type ChannelsOptions

type ChannelsOptions struct {
	// Pattern to filter channels.
	Pattern string `json:"pattern,omitempty"`
}

ChannelsOptions define some fields to alter Channels method behaviour.

type ChannelsResult

type ChannelsResult struct {
	Channels map[string]ChannelInfo `json:"channels"`
}

ChannelsResult is a result of channels command.

type Client

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

Client is API client for project registered in server.

func New

func New(c Config) *Client

New returns initialized client instance based on provided config.

func (*Client) Broadcast

func (c *Client) Broadcast(ctx context.Context, channels []string, data []byte, opts ...PublishOption) (BroadcastResult, error)

Broadcast allows to broadcast the same data into many channels..

func (*Client) Channels

func (c *Client) Channels(ctx context.Context, opts ...ChannelsOption) (ChannelsResult, error)

Channels returns information about active channels (with one or more subscribers) on server.

func (*Client) Disconnect

func (c *Client) Disconnect(ctx context.Context, user string, opts ...DisconnectOption) error

Disconnect allows to close all connections of user to server.

func (*Client) History

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

History returns channel history.

func (*Client) HistoryRemove

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

HistoryRemove removes channel history.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (InfoResult, error)

Info returns information about server nodes.

func (*Client) Pipe

func (c *Client) Pipe() *Pipe

Pipe allows to create new Pipe to send several commands in one HTTP request.

func (*Client) Presence

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

Presence returns channel presence information.

func (*Client) PresenceStats

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

PresenceStats returns short channel presence information (only counters).

func (*Client) Publish

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

Publish allows to publish data to channel.

func (*Client) SendPipe

func (c *Client) SendPipe(ctx context.Context, pipe *Pipe) ([]Reply, error)

SendPipe sends Commands collected in Pipe to Centrifugo. Using this method you should manually inspect all replies.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

SetHTTPClient allows to set custom http Client to use for requests. Not goroutine-safe.

func (*Client) Subscribe added in v3.1.0

func (c *Client) Subscribe(ctx context.Context, channel, user string, opts ...SubscribeOption) error

Subscribe allow subscribing user to a channel (using server-side subscriptions).

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(ctx context.Context, channel, user string, opts ...UnsubscribeOption) error

Unsubscribe allows to unsubscribe user from channel.

type ClientInfo

type ClientInfo struct {
	User     string          `json:"user"`
	Client   string          `json:"client"`
	ConnInfo json.RawMessage `json:"conn_info,omitempty"`
	ChanInfo json.RawMessage `json:"chan_info,omitempty"`
}

ClientInfo represents information about one client connection to Centrifugo. This struct used in messages published by clients, join/leave events, presence data.

type Command

type Command struct {
	Method string      `json:"method"`
	Params interface{} `json:"params"`
}

Command represents API command to send.

type Config

type Config struct {
	// Addr is Centrifugo API endpoint.
	Addr string
	// GetAddr when set will be used before every API call to extract
	// Centrifugo API endpoint. In this case Addr field of Config will be
	// ignored. Nil value means using static Config.Addr field.
	GetAddr func() (string, error)
	// Key is Centrifugo API key.
	Key string
	// HTTPClient is a custom HTTP client to be used.
	// If nil DefaultHTTPClient will be used.
	HTTPClient *http.Client
}

Config of client.

type Disconnect

type Disconnect struct {
	// Code is disconnect code.
	Code uint32 `json:"code,omitempty"`
	// Reason is a short description of disconnect.
	Reason string `json:"reason"`
	// Reconnect gives client an advice to reconnect after disconnect or not.
	Reconnect bool `json:"reconnect"`
}

Disconnect allows to configure how client will be disconnected from server. The important note that Disconnect serialized to JSON must be less than 127 bytes due to WebSocket protocol limitations (because at moment we send Disconnect inside reason field of WebSocket close handshake).

type DisconnectOption

type DisconnectOption func(options *DisconnectOptions)

DisconnectOption is a type to represent various Disconnect options.

func WithDisconnect

func WithDisconnect(disconnect *Disconnect) DisconnectOption

WithDisconnect allows to set custom Disconnect.

func WithDisconnectClient

func WithDisconnectClient(clientID string) DisconnectOption

WithDisconnectClient allows to set Client.

func WithDisconnectClientWhitelist

func WithDisconnectClientWhitelist(whitelist []string) DisconnectOption

WithDisconnectClientWhitelist allows to set ClientWhitelist.

type DisconnectOptions

type DisconnectOptions struct {
	// Disconnect represents custom disconnect to use.
	// By default DisconnectForceNoReconnect will be used.
	Disconnect *Disconnect
	// ClientWhitelist contains client IDs to keep.
	ClientWhitelist []string
	// ClientID to disconnect.
	ClientID string `json:"client,omitempty"`
}

DisconnectOptions define some fields to alter behaviour of Disconnect operation.

type ErrStatusCode

type ErrStatusCode struct {
	Code int
}

ErrStatusCode can be returned in case request to server resulted in wrong status code.

func (ErrStatusCode) Error

func (e ErrStatusCode) Error() string

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents API request error.

func (Error) Error

func (e Error) Error() string

type HistoryOption

type HistoryOption func(options *HistoryOptions)

HistoryOption is a type to represent various History options.

func WithLimit

func WithLimit(limit int) HistoryOption

WithLimit allows to set HistoryOptions.Limit.

func WithReverse

func WithReverse(reverse bool) HistoryOption

WithSince allows to set HistoryOptions.Since option.

func WithSince

func WithSince(sp *StreamPosition) HistoryOption

WithSince allows to set HistoryOptions.Since option.

type HistoryOptions

type HistoryOptions struct {
	// Since used to extract publications from stream since provided StreamPosition.
	Since *StreamPosition `json:"since,omitempty"`
	// Limit number of publications to return.
	// -1 means no limit - i.e. return all publications currently in stream.
	// 0 means that caller only interested in current stream top position so
	// Broker should not return any publications in result.
	// Positive integer does what it should.
	Limit int `json:"limit,omitempty"`
	// Reverse direction.
	Reverse bool `json:"reverse,omitempty"`
}

HistoryOptions define some fields to alter History method behaviour.

type HistoryResult

type HistoryResult struct {
	Publications []Publication `json:"publications"`
	Offset       uint64        `json:"offset"`
	Epoch        string        `json:"epoch"`
}

HistoryResult is a result of history command.

type InfoResult

type InfoResult struct {
	Nodes []NodeInfo `json:"nodes"`
}

InfoResult is a result of info command.

type NodeInfo

type NodeInfo struct {
	// UID is a unique id of running node.
	UID string `json:"uid"`
	// Name is a name of node (config defined or generated automatically).
	Name string `json:"name"`
	// Version of Centrifugo node.
	Version string `json:"version"`
	// NumClients is a number of clients connected to node.
	NumClients int `json:"num_clients"`
	// NumUsers is a number of unique users connected to node.
	NumUsers int `json:"num_users"`
	// NumChannels is a number of channels on node.
	NumChannels int `json:"num_channels"`
	// Uptime of node in seconds.
	Uptime int `json:"uptime"`
}

NodeInfo contains information and statistics about Centrifugo node.

type Pipe

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

Pipe allows to send several commands in one HTTP request.

func (*Pipe) AddBroadcast

func (p *Pipe) AddBroadcast(channels []string, data []byte, opts ...PublishOption) error

AddBroadcast adds broadcast command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddChannels

func (p *Pipe) AddChannels(opts ...ChannelsOption) error

AddChannels adds channels command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddDisconnect

func (p *Pipe) AddDisconnect(user string, opts ...DisconnectOption) error

AddDisconnect adds disconnect command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddHistory

func (p *Pipe) AddHistory(channel string, opts ...HistoryOption) error

AddHistory adds history command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddHistoryRemove

func (p *Pipe) AddHistoryRemove(channel string) error

AddHistoryRemove adds history remove command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddInfo

func (p *Pipe) AddInfo() error

AddInfo adds info command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddPresence

func (p *Pipe) AddPresence(channel string) error

AddPresence adds presence command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddPresenceStats

func (p *Pipe) AddPresenceStats(channel string) error

AddPresenceStats adds presence stats command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddPublish

func (p *Pipe) AddPublish(channel string, data []byte, opts ...PublishOption) error

AddPublish adds publish command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddSubscribe added in v3.1.0

func (p *Pipe) AddSubscribe(channel string, user string, opts ...SubscribeOption) error

AddSubscribe adds subscribe command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) AddUnsubscribe

func (p *Pipe) AddUnsubscribe(channel string, user string, opts ...UnsubscribeOption) error

AddUnsubscribe adds unsubscribe command to client command buffer but not actually sends request to server until Pipe will be explicitly sent.

func (*Pipe) Reset

func (p *Pipe) Reset()

Reset allows to clear client command buffer.

type PresenceResult

type PresenceResult struct {
	Presence map[string]ClientInfo `json:"presence"`
}

PresenceResult is a result of presence command.

type PresenceStatsResult

type PresenceStatsResult struct {
	NumUsers   int32 `json:"num_users"`
	NumClients int32 `json:"num_clients"`
}

PresenceStatsResult is a result of info command.

type Publication

type Publication struct {
	Offset uint64          `json:"offset"`
	Data   json.RawMessage `json:"data"`
	Info   *ClientInfo     `json:"info"`
}

Publication represents message published into channel.

type PublishOption

type PublishOption func(*PublishOptions)

PublishOption is a type to represent various Publish options.

func WithSkipHistory

func WithSkipHistory(skip bool) PublishOption

WithSkipHistory allows to set SkipHistory field.

type PublishOptions

type PublishOptions struct {
	SkipHistory bool `json:"skip_history,omitempty"`
}

type PublishResponse

type PublishResponse struct {
	Error  *Error         `json:"error"`
	Result *PublishResult `json:"result"`
}

type PublishResult

type PublishResult struct {
	Offset uint64 `json:"offset"`
	Epoch  string `json:"epoch"`
}

PublishResult is a result of publish command.

type Reply

type Reply struct {
	Error  *Error          `json:"error"`
	Result json.RawMessage `json:"result"`
}

Reply is a server response to command.

type StreamPosition

type StreamPosition struct {
	// Offset defines publication incremental offset inside a stream.
	Offset uint64 `json:"offset,omitempty"`
	// Epoch allows handling situations when storage
	// lost stream entirely for some reason (expired or lost after restart) and we
	// want to track this fact to prevent successful recovery from another stream.
	// I.e. for example we have stream [1, 2, 3], then it's lost and new stream
	// contains [1, 2, 3, 4], client that recovers from position 3 will only receive
	// publication 4 missing 1, 2, 3 from new stream. With epoch we can tell client
	// that correct recovery is not possible.
	Epoch string `json:"epoch,omitempty"`
}

StreamPosition contains fields to describe position in stream. At moment this is used for automatic recovery mechanics. More info about stream recovery in docs: https://centrifugal.github.io/centrifugo/server/recover/.

type SubscribeOption

type SubscribeOption func(*SubscribeOptions)

SubscribeOption is a type to represent various Subscribe options.

func WithJoinLeave

func WithJoinLeave(enabled bool) SubscribeOption

WithJoinLeave ...

func WithPosition

func WithPosition(enabled bool) SubscribeOption

WithPosition ...

func WithPresence

func WithPresence(enabled bool) SubscribeOption

WithPresence ...

func WithRecover

func WithRecover(enabled bool) SubscribeOption

WithRecover ...

func WithRecoverSince

func WithRecoverSince(since *StreamPosition) SubscribeOption

WithRecoverSince allows setting SubscribeOptions.RecoverFrom.

func WithSubscribeClient

func WithSubscribeClient(clientID string) SubscribeOption

WithSubscribeClient allows setting client ID that should be subscribed. This option not used when Client.Subscribe called.

func WithSubscribeData

func WithSubscribeData(data json.RawMessage) SubscribeOption

WithSubscribeData allows setting custom data to send with subscribe push.

func WithSubscribeInfo

func WithSubscribeInfo(chanInfo json.RawMessage) SubscribeOption

WithSubscribeInfo ...

type SubscribeOptions

type SubscribeOptions struct {
	// ChannelInfo defines custom channel information, zero value means no channel information.
	Info json.RawMessage `json:"info,omitempty"`
	// Presence turns on participating in channel presence.
	Presence bool `json:"presence,omitempty"`
	// JoinLeave enables sending Join and Leave messages for this client in channel.
	JoinLeave bool `json:"join_leave,omitempty"`
	// When position is on client will additionally sync its position inside
	// a stream to prevent message loss. Make sure you are enabling Position in channels
	// that maintain Publication history stream. When Position is on  Centrifuge will
	// include StreamPosition information to subscribe response - for a client to be able
	// to manually track its position inside a stream.
	Position bool `json:"position,omitempty"`
	// Recover turns on recovery option for a channel. In this case client will try to
	// recover missed messages automatically upon resubscribe to a channel after reconnect
	// to a server. This option also enables client position tracking inside a stream
	// (like Position option) to prevent occasional message loss. Make sure you are using
	// Recover in channels that maintain Publication history stream.
	Recover bool `json:"recover,omitempty"`
	// Data to send to a client with Subscribe Push.
	Data json.RawMessage `json:"data,omitempty"`
	// RecoverSince will try to subscribe a client and recover from a certain StreamPosition.
	RecoverSince *StreamPosition `json:"recover_since,omitempty"`
	// ClientID to subscribe.
	ClientID string `json:"client,omitempty"`
}

SubscribeOptions define per-subscription options.

type UnsubscribeOption

type UnsubscribeOption func(options *UnsubscribeOptions)

UnsubscribeOption is a type to represent various Unsubscribe options.

func WithUnsubscribeClient

func WithUnsubscribeClient(clientID string) UnsubscribeOption

WithUnsubscribeClient allows setting client ID that should be unsubscribed. This option not used when Client.Unsubscribe called.

type UnsubscribeOptions

type UnsubscribeOptions struct {
	// ClientID to unsubscribe.
	ClientID string `json:"client,omitempty"`
}

UnsubscribeOptions ...

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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