gocent

package module
v0.0.0-...-d192cc5 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2022 License: MIT Imports: 12 Imported by: 1

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/scarbo87/gocent

License

Gocent is available under the MIT license.

Documentation

Overview

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

Usage example

In example below we initialize new client with server URL address, project secret and request timeout. Then publish data into channel, call presence and history for channel and finally show how to publish several messages in one POST request to API endpoint using internal command buffer.

c := NewClient("http://localhost:8000", "secret", 5*time.Second)

ok, err := c.Publish("$public:chat", []byte(`{"input": "test"}`))
if err != nil {
	println(err.Error())
	return
}
println("Publish successful:", ok)

presence, _ := c.Presence("$public:chat")
fmt.Printf("Presense: %v\n", presence)

history, _ := c.History("$public:chat")
fmt.Printf("History: %v\n", history)

channels, _ := c.Channels()
fmt.Printf("Channels: %v\n", channels)

stats, _ := c.Stats()
fmt.Printf("Stats: %v\n", stats)

_ = c.AddPublish("$public:chat", []byte(`{"input": "test1"}`))
_ = c.AddPublish("$public:chat", []byte(`{"input": "test2"}`))
_ = c.AddPublish("$public:chat", []byte(`{"input": "test3"}`))

result, err := c.Send()
println("Sent", len(result), "publish commands in one request")

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientNotEmpty can be returned when client with non empty commands buffer
	// is used for single command send.
	ErrClientNotEmpty = errors.New("client command buffer not empty, send commands or reset client")
	// ErrMalformedResponse can be returned when server replied with invalid response.
	ErrMalformedResponse = errors.New("malformed response returned from server")
)

Functions

func DecodeBroadcast

func DecodeBroadcast(body []byte) (bool, error)

DecodeBroadcast allows to decode response body of broadcast command to get success flag from it. Currently no error in response means success - so nothing to do here yet.

func DecodeChannels

func DecodeChannels(body []byte) ([]string, error)

DecodeChannels allows to decode channels command response body to get a slice of channels.

func DecodeDisconnect

func DecodeDisconnect(body []byte) (bool, error)

DecodeDisconnect allows to decode response body of disconnect command to get success flag from it. Currently no error in response means success - so nothing to do here yet.

func DecodePresence

func DecodePresence(body []byte) (map[string]ClientInfo, error)

DecodePresence allows to decode presence response body to get a map of clients.

func DecodePublish

func DecodePublish(body []byte) (bool, error)

DecodePublish allows to decode response body of publish command to get success flag from it. Currently no error in response means success - so nothing to do here yet.

func DecodeUnsubscribe

func DecodeUnsubscribe(body []byte) (bool, error)

DecodeUnsubscribe allows to decode response body of unsubscribe command to get success flag from it. Currently no error in response means success - so nothing to do here yet.

func GenerateAPISign

func GenerateAPISign(secret string, data []byte) string

GenerateAPISign generates sign which is used to sign HTTP API requests.

func GenerateChannelSign

func GenerateChannelSign(secret, client, channel, channelData string) string

GenerateChannelSign generates sign which is used to prove permission of client to subscribe on private channel.

func GenerateClientToken

func GenerateClientToken(secret, user, timestamp, info string) string

GenerateClientToken generates client token based on secret key and provided connection parameters such as user ID, timestamp and info JSON string.

Types

type Client

type Client struct {
	Endpoint string
	Secret   string
	Timeout  time.Duration
	// contains filtered or unexported fields
}

Client is API client for project registered in server.

func NewClient

func NewClient(addr, secret string, timeout time.Duration, transport *http.Transport) *Client

NewClient returns initialized client instance based on provided server address, project key, project secret, timeout and http.Transport settings

func NewInsecureAPIClient

func NewInsecureAPIClient(addr string, timeout time.Duration, transport *http.Transport) *Client

NewInsecureAPIClient allows to create client that won't sign every HTTP API request. This is useful when your Centrifugo /api/ endpoint protected by firewall.

func (*Client) AddBroadcast

func (c *Client) AddBroadcast(channels []string, data []byte) error

AddBroadcast adds broadcast command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddBroadcastClient

func (c *Client) AddBroadcastClient(channels []string, data []byte, client string) error

AddBroadcastClient adds broadcast command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddChannels

func (c *Client) AddChannels() error

AddChannels adds channels command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddDisconnect

func (c *Client) AddDisconnect(user string) error

AddDisconnect adds disconnect command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddHistory

func (c *Client) AddHistory(channel string) error

AddHistory adds history command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddPresence

func (c *Client) AddPresence(channel string) error

AddPresence adds presence command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddPublish

func (c *Client) AddPublish(channel string, data []byte) error

AddPublish adds publish command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddPublishClient

func (c *Client) AddPublishClient(channel string, data []byte, client string) error

AddPublishClient adds publish command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddStats

func (c *Client) AddStats() error

AddStats adds stats command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) AddUnsubscribe

func (c *Client) AddUnsubscribe(channel string, user string) error

AddUnsubscribe adds unsubscribe command to client command buffer but not actually send it until Send method explicitly called.

func (*Client) Broadcast

func (c *Client) Broadcast(channels []string, data []byte) (bool, error)

Broadcast sends broadcast command to server.

func (*Client) BroadcastClient

func (c *Client) BroadcastClient(channels []string, data []byte, client string) (bool, error)

BroadcastClient sends broadcast command to server with client ID.

func (*Client) Channels

func (c *Client) Channels() ([]string, error)

Channels sends channels command to server and returns slice with active channels (with one or more subscribers).

func (*Client) Disconnect

func (c *Client) Disconnect(user string) (bool, error)

Disconnect sends disconnect command to server and returns boolean indicator of success and any error occurred in process.

func (*Client) History

func (c *Client) History(channel string) ([]Message, error)

History sends history command for channel to server and returns slice with messages and any error occurred in process.

func (*Client) Presence

func (c *Client) Presence(channel string) (map[string]ClientInfo, error)

Presence sends presence command for channel to server and returns map with client information and any error occurred in process.

func (*Client) Publish

func (c *Client) Publish(channel string, data []byte) (bool, error)

Publish sends publish command to server and returns boolean indicator of success and any error occurred in process.

func (*Client) PublishClient

func (c *Client) PublishClient(channel string, data []byte, client string) (bool, error)

PublishClient sends publish command to server and returns boolean indicator of success and any error occurred in process. `client` is client ID initiating this event.

func (*Client) Reset

func (c *Client) Reset()

Reset allows to clear client command buffer.

func (*Client) Send

func (c *Client) Send() (Result, error)

Send actually makes API POST request to server sending all buffered commands in one request. Using this method you should manually decode all responses in returned Result.

func (*Client) Stats

func (c *Client) Stats() (Stats, error)

Stats sends stats command to server and returns Stats.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(channel, user string) (bool, error)

Unsubscribe sends unsubscribe command to server and returns boolean indicator of success and any error occurred in process.

type ClientInfo

type ClientInfo struct {
	User        string           `json:"user"`
	Client      string           `json:"client"`
	DefaultInfo *json.RawMessage `json:"default_info,omitempty"`
	ChannelInfo *json.RawMessage `json:"channel_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 {
	UID    string                 `json:"uid"`
	Method string                 `json:"method"`
	Params map[string]interface{} `json:"params"`
}

Command represents API command to send.

type Message

type Message struct {
	UID       string           `json:"uid"`
	Timestamp string           `json:"timestamp"`
	Info      *ClientInfo      `json:"info,omitempty"`
	Channel   string           `json:"channel"`
	Data      *json.RawMessage `json:"data"`
	Client    string           `json:"client,omitempty"`
}

Message represents message published into channel.

func DecodeHistory

func DecodeHistory(body []byte) ([]Message, error)

DecodeHistory allows to decode history response body to get a slice of messages.

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"`
	// Started is node start timestamp.
	Started int64 `json:"started_at"`
	// Metrics contains Centrifugo metrics.
	Metrics map[string]int64 `json:"metrics"`
}

NodeInfo contains information and statistics about Centrifugo node.

type Response

type Response struct {
	Method string          `json:"method"`
	Error  string          `json:"error"`
	Body   json.RawMessage `json:"body"`
}

Response is a response of server on command sent.

type Result

type Result []Response

Result is a slice of responses.

type Stats

type Stats struct {
	Nodes           []NodeInfo `json:"nodes"`
	MetricsInterval int64      `json:"metrics_interval"`
}

Stats contains state and metrics information from all running Centrifugo nodes.

func DecodeStats

func DecodeStats(body []byte) (Stats, error)

DecodeStats allows to decode stats command response body.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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