wspubsub

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2020 License: MIT Imports: 21 Imported by: 0

README

WSPubSub

CircleCI Build Status Coverage Status GoDoc MIT Licensed

WSPubSub library is a Go implementation of channels based pub/sub pattern over WebSocket protocol.

This library completely hides interaction with the transport layer like: connection upgrading, disconnecting, ping/pong etc. Thanks to this, you can focus only on your tasks.

Client interaction with the library mainly occurs through the hub API. The only two steps to publish messages are required:

  • Register receive handler using hub.OnReceive
  • Subscribe clients using hub.Subscribe

Now you are ready to publish messages to different channels using hub.Publish. Users who have been subscribed to those channels will receive the messages!

Install

Use go get to install the latest version of the library:

go get github.com/kpeu3i/wspubsub

Next, include wspubsub in your application:

import "github.com/kpeu3i/wspubsub"

Usage

A minimal working example is listed below:

package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/kpeu3i/wspubsub"
	"github.com/pkg/errors"
)

type Message struct {
	Command  string   `json:"command"`
	Channels []string `json:"channels"`
}

func main() {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	channels := []string{"general", "public", "private"}
	messageFormat := `{"now": %d}`

	hub := wspubsub.NewDefaultHub()
	defer hub.Close()

	publishTicker := time.NewTicker(1 * time.Second)
	defer publishTicker.Stop()

	hub.OnReceive(func(clientID wspubsub.UUID, message wspubsub.Message) {
		m := Message{}
		err := json.Unmarshal(message.Payload, &m)
		if err != nil {
			hub.LogError(errors.Wrap(err, "hub.on_receive.unmarshal"))
			return
		}

		switch m.Command {
		case "SUBSCRIBE":
			err := hub.Subscribe(clientID, m.Channels...)
			if err != nil {
				hub.LogError(errors.Wrap(err, "hub.on_receive.subscribe"))
			}
		case "UNSUBSCRIBE":
			err := hub.Unsubscribe(clientID, m.Channels...)
			if err != nil {
				hub.LogError(errors.Wrap(err, "hub.on_receive.unsubscribe"))
			}
		}
	})

	go func() {
		err := hub.ListenAndServe("localhost:8080", "/")
		if err != nil {
			hub.LogPanic(err)
		}
	}()

	go func() {
		for range publishTicker.C {
			// Pick a random channel
			channel := channels[rand.Intn(len(channels))]
			message := wspubsub.NewTextMessageFromString(fmt.Sprintf(messageFormat, time.Now().Unix()))
			_, err := hub.Publish(message, channel)
			if err != nil {
				hub.LogPanic(err)
			}

			hub.LogInfof("Published: channel=%s, message=%s\n", channel, string(message.Payload))
		}
	}()

	<-quit
}

More examples you can find in examples directory.

Lint and test

First, you need to install project dependencies (golangci, mockgen, etc):

$ make deps-install

Now, you are able to run:

$ make lint
$ make test

If it required to update mocks use the following command:

$ make mocks-generate

Contributing

Please don't hesitate to fork the project and send a pull request me to ask questions and share ideas.

  1. Fork it
  2. Download the fork (git clone https://github.com/kpeu3i/wspubsub.git && cd wspubsub)
  3. Create your feature branch (git checkout -b my-new-feature)
  4. Make changes and add them (git add .)
  5. Commit your changes (git commit -m 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new pull request

License

This library is released under the MIT license. See the LICENSE file for details.

Documentation

Overview

Package wspubsub provides an easy way to publish/subscribe and receive messages over WebSocket protocol hiding the details of the underlying transport. The library based on the idea that all messages are published to channels. Subscribers will receive messages published to the channels to which they subscribe. The hub is responsible for defining the channels to which subscribers can subscribe.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client represents a connection to the WebSocket server.

func NewClient

func NewClient(options ClientOptions, id UUID, upgrader WebsocketConnectionUpgrader, logger Logger) *Client

NewClient initializes a new Client.

func (*Client) Close

func (c *Client) Close() error

Close closes a client connection.

func (*Client) Connect

func (c *Client) Connect(response http.ResponseWriter, request *http.Request) error

Connect upgrades the HTTP server connection to the WebSocket protocol.

func (*Client) ID

func (c *Client) ID() UUID

ID returns unique client id.

func (*Client) OnError

func (c *Client) OnError(handler ErrorHandler)

OnError registers a handler for errors occurred while reading or writing connection.

func (*Client) OnReceive

func (c *Client) OnReceive(handler ReceiveHandler)

OnReceive registers a handler for incoming messages.

func (*Client) Send

func (c *Client) Send(message Message) error

Send writes a message to client connection asynchronously.

type ClientConnectError

type ClientConnectError struct {
	ID  UUID
	Err error
}

ClientConnectError returned when HTTP connection can't be upgraded to WebSocket connection.

func IsClientConnectError

func IsClientConnectError(err error) (*ClientConnectError, bool)

IsClientConnectError checks if error type is ClientConnectError.

func NewClientConnectError

func NewClientConnectError(id UUID, err error) *ClientConnectError

NewClientConnectError initializes a new ClientConnectError.

func (*ClientConnectError) Error

func (e *ClientConnectError) Error() string

ClientConnectError implements an error interface.

type ClientFactory

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

ClientFactory is responsible for creating a client.

func NewClientFactory

func NewClientFactory(
	options ClientOptions,
	uuidGenerator UUIDGenerator,
	upgrader WebsocketConnectionUpgrader,
	logger Logger,
) *ClientFactory

NewClientFactory initializes a new ClientFactory.

func (*ClientFactory) Create

func (f *ClientFactory) Create() WebsocketClient

Create returns a new client.

type ClientNotFoundError

type ClientNotFoundError struct {
	ID UUID
}

ClientNotFoundError returned when client is not present in a storage.

func IsClientNotFoundError

func IsClientNotFoundError(err error) (*ClientNotFoundError, bool)

IsClientNotFoundError checks if error type is ClientNotFoundError.

func NewClientNotFoundError

func NewClientNotFoundError(id UUID) *ClientNotFoundError

NewClientNotFoundError initializes a new ClientNotFoundError.

func (*ClientNotFoundError) Error

func (e *ClientNotFoundError) Error() string

ClientNotFoundError implements an error interface.

type ClientOptions

type ClientOptions struct {
	// How often pings will be sent by the client.
	PingInterval time.Duration

	// Max size of the buffer for messages which client should
	// write to a WebSocket connection.
	// Exceeding this size will cause an error.
	SendBufferSize int

	// Enable/disable debug mode.
	IsDebug bool

	// Function execution time limit in debug mode.
	// Exceeding this time limit will cause a new warn log message.
	DebugFuncTimeLimit time.Duration
}

ClientOptions represents configuration of the client.

func NewClientOptions

func NewClientOptions() ClientOptions

NewClientOptions initializes a new ClientOptions. nolint: gomnd

type ClientPingError

type ClientPingError struct {
	ID      UUID
	Message Message
	Err     error
}

ClientPingError returned when ping message can't be written to a WebSocket connection.

func IsClientPingError

func IsClientPingError(err error) (*ClientPingError, bool)

IsClientPingError checks if error type is ClientPingError.

func NewClientPingError

func NewClientPingError(id UUID, message Message, err error) *ClientPingError

NewClientPingError initializes a new ClientPingError.

func (*ClientPingError) Error

func (e *ClientPingError) Error() string

ClientPingError implements an error interface.

type ClientReceiveError

type ClientReceiveError struct {
	ID      UUID
	Message Message
	Err     error
}

ClientReceiveError returned when message can't be read from a WebSocket connection.

func IsClientReceiveError

func IsClientReceiveError(err error) (*ClientReceiveError, bool)

IsClientReceiveError checks if error type is ClientReceiveError.

func NewClientReceiveError

func NewClientReceiveError(id UUID, message Message, err error) *ClientReceiveError

NewClientReceiveError initializes a new ClientReceiveError.

func (*ClientReceiveError) Error

func (e *ClientReceiveError) Error() string

ClientReceiveError implements an error interface.

type ClientRepeatConnectError

type ClientRepeatConnectError struct {
	ID UUID
}

ClientRepeatConnectError returned when trying to connect an already connected client.

func IsClientRepeatConnectError

func IsClientRepeatConnectError(err error) (*ClientRepeatConnectError, bool)

IsClientRepeatConnectError checks if error type is ClientRepeatConnectError.

func NewClientRepeatConnectError

func NewClientRepeatConnectError(id UUID) *ClientRepeatConnectError

NewClientRepeatConnectError initializes a new ClientRepeatConnectError.

func (*ClientRepeatConnectError) Error

func (e *ClientRepeatConnectError) Error() string

ClientRepeatConnectError implements an error interface.

type ClientSendBufferOverflowError

type ClientSendBufferOverflowError struct {
	ID UUID
}

ClientSendBufferOverflowError returned when client send buffer is full.

func IsClientSendBufferOverflowError

func IsClientSendBufferOverflowError(err error) (*ClientSendBufferOverflowError, bool)

IsClientSendBufferOverflowError checks if error type is ClientSendBufferOverflowError.

func NewClientSendBufferOverflowError

func NewClientSendBufferOverflowError(id UUID) *ClientSendBufferOverflowError

NewClientSendBufferOverflowError initializes a new ClientSendBufferOverflowError.

func (*ClientSendBufferOverflowError) Error

ClientSendBufferOverflowError implements an error interface.

type ClientSendError

type ClientSendError struct {
	ID      UUID
	Message Message
	Err     error
}

ClientSendError returned when a message (text or binary) can't be written to a WebSocket connection.

func IsClientSendError

func IsClientSendError(err error) (*ClientSendError, bool)

IsClientSendError checks if error type is ClientSendError.

func NewClientSendError

func NewClientSendError(id UUID, message Message, err error) *ClientSendError

NewClientSendError initializes a new ClientSendError.

func (*ClientSendError) Error

func (e *ClientSendError) Error() string

ClientSendError implements an error interface.

type ClientStore

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

ClientStore represents the storage of clients.

func NewClientStore

func NewClientStore(options ClientStoreOptions, logger Logger) *ClientStore

NewClientStore initializes a new ClientStore.

func (*ClientStore) Channels

func (s *ClientStore) Channels(clientID UUID) ([]string, error)

CountChannels return a list of channels linked with the client.

func (*ClientStore) Count

func (s *ClientStore) Count(channels ...string) int

Count returns the total number of clients in specified channel(-s).

func (*ClientStore) CountChannels

func (s *ClientStore) CountChannels(clientID UUID) (int, error)

CountChannels return the total number of channels linked with the client.

func (*ClientStore) Find

func (s *ClientStore) Find(fn IterateFunc, channels ...string) error

Find iterates over clients who subscribed on specified channel(-s).

func (*ClientStore) Get

func (s *ClientStore) Get(clientID UUID) (WebsocketClient, error)

Get returns client by its ID.

func (*ClientStore) Set

func (s *ClientStore) Set(client WebsocketClient)

Set puts client to storage.

func (*ClientStore) SetChannels

func (s *ClientStore) SetChannels(clientID UUID, channels ...string) error

SetChannels links the client with specified channel(-s).

func (*ClientStore) Unset

func (s *ClientStore) Unset(clientID UUID) error

Unset removes client from storage by its ID

func (*ClientStore) UnsetChannels

func (s *ClientStore) UnsetChannels(clientID UUID, channels ...string) error

SetChannels unlinks the client from specified channel(-s). If channels were not specified then the client will be unlinked from all channels.

type ClientStoreOptions

type ClientStoreOptions struct {
	ClientShards struct {
		// Total number of shards
		Count int

		// Size of shard
		Size int

		// Size of a bucket in shard
		BucketSize int
	}
	ChannelShards struct {
		// Total number of shards
		Count int

		// Size of shard
		Size int

		// Size of a bucket in shard
		BucketSize int
	}

	// Enable/disable debug mode.
	IsDebug bool

	// Function execution time limit in debug mode.
	// Exceeding this time limit will cause a new warn log message.
	DebugFuncTimeLimit time.Duration
}

ClientStoreOptions represents configuration of the storage.

func NewClientStoreOptions

func NewClientStoreOptions() ClientStoreOptions

NewClientStoreOptions initializes a new ClientStoreOptions. nolint: gomnd

type ConnectHandler

type ConnectHandler func(clientID UUID)

ConnectHandler called when a new client is connected to hub.

type ConnectionClosedError

type ConnectionClosedError struct {
	Err error
}

ConnectionClosedError returned when trying to read or write to closed WebSocket connection.

func IsConnectionClosedError

func IsConnectionClosedError(err error) (*ConnectionClosedError, bool)

IsConnectionClosedError checks if error type is ConnectionClosedError.

func NewConnectionClosedError

func NewConnectionClosedError(err error) *ConnectionClosedError

NewConnectionClosedError initializes a new ConnectionClosedError.

func (*ConnectionClosedError) Error

func (e *ConnectionClosedError) Error() string

ConnectionClosedError implements an error interface.

type DisconnectHandler

type DisconnectHandler func(clientID UUID)

DisconnectHandler called when a client is disconnected from the hub.

type ErrorHandler

type ErrorHandler func(clientID UUID, err error)

ErrorHandler called when an error occurred when reading or writing messages.

type GobwasConnection

type GobwasConnection struct {
	IsDebug            bool
	DebugFuncTimeLimit time.Duration
	// contains filtered or unexported fields
}

GobwasConnection is an implementation of WebsocketConnection.

func (*GobwasConnection) Close

func (c *GobwasConnection) Close() error

Close closes a WebSocket connection.

func (*GobwasConnection) Read

func (c *GobwasConnection) Read() (Message, error)

Read reads a message from WebSocket connection.

func (*GobwasConnection) Write

func (c *GobwasConnection) Write(message Message) error

Write writes a message to WebSocket connection.

type GobwasConnectionUpgrader

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

GobwasConnectionUpgrader is an implementation of WebsocketConnectionUpgrader.

func NewGobwasConnectionUpgrader

func NewGobwasConnectionUpgrader(options GobwasConnectionUpgraderOptions, logger Logger) *GobwasConnectionUpgrader

NewGobwasConnectionUpgrader initializes a new GobwasConnectionUpgrader.

func (*GobwasConnectionUpgrader) Upgrade

GobwasConnectionUpgrader upgrades HTTP connection to the WebSocket connection.

type GobwasConnectionUpgraderOptions

type GobwasConnectionUpgraderOptions struct {
	ReadTimout         time.Duration
	WriteTimout        time.Duration
	IsDebug            bool
	DebugFuncTimeLimit time.Duration
}

GobwasConnectionUpgraderOptions represents configuration of the GobwasConnectionUpgrader.

func NewGobwasConnectionUpgraderOptions

func NewGobwasConnectionUpgraderOptions() GobwasConnectionUpgraderOptions

NewGobwasUpgraderOptions initializes a new GobwasConnectionUpgraderOptions. nolint: gomnd

type GorillaConnection

type GorillaConnection struct {
	IsDebug            bool
	DebugFuncTimeLimit time.Duration
	// contains filtered or unexported fields
}

GorillaConnection is an implementation of WebsocketConnection.

func (*GorillaConnection) Close

func (c *GorillaConnection) Close() error

Close closes a WebSocket connection.

func (*GorillaConnection) Read

func (c *GorillaConnection) Read() (Message, error)

Read reads a message from WebSocket connection.

func (*GorillaConnection) Write

func (c *GorillaConnection) Write(message Message) error

Write writes a message to WebSocket connection.

type GorillaConnectionUpgrader

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

GorillaConnectionUpgrader is an implementation of WebsocketConnectionUpgrader.

func NewGorillaConnectionUpgrader

func NewGorillaConnectionUpgrader(options GorillaConnectionUpgraderOptions, logger Logger) *GorillaConnectionUpgrader

NewGorillaConnectionUpgrader initializes a new GorillaConnectionUpgrader.

func (*GorillaConnectionUpgrader) Upgrade

GorillaConnectionUpgrader upgrades HTTP connection to the WebSocket connection.

type GorillaConnectionUpgraderOptions

type GorillaConnectionUpgraderOptions struct {
	MaxMessageSize     int64
	ReadTimout         time.Duration
	WriteTimout        time.Duration
	HandshakeTimeout   time.Duration
	ReadBufferSize     int
	WriteBufferSize    int
	Subprotocols       []string
	Error              func(w http.ResponseWriter, r *http.Request, status int, reason error)
	CheckOrigin        func(r *http.Request) bool
	EnableCompression  bool
	IsDebug            bool
	DebugFuncTimeLimit time.Duration
}

GorillaConnectionUpgraderOptions represents configuration of the GorillaConnectionUpgrader.

func NewGorillaConnectionUpgraderOptions

func NewGorillaConnectionUpgraderOptions() GorillaConnectionUpgraderOptions

NewGorillaConnectionUpgraderOptions initializes a new GorillaConnectionUpgraderOptions. nolint: gomnd

type Hub

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

Hub manages client connections.

func NewDefaultHub

func NewDefaultHub() *Hub

NewDefaultHub uses default dependencies to initializes a new hub.

func NewHub

func NewHub(
	options HubOptions,
	clientStore WebsocketClientStore,
	clientFactory WebsocketClientFactory,
	logger Logger,
) *Hub

NewHub initializes a new Hub.

func (*Hub) Channels

func (h *Hub) Channels(clientID UUID) ([]string, error)

Channels return a list of channels the client currently subscribed to.

func (*Hub) Close

func (h *Hub) Close() error

Close shutdowns http-servers and disconnects clients.

func (*Hub) Count

func (h *Hub) Count(channels ...string) int

Count returns total number of connected clients.

func (*Hub) Disconnect

func (h *Hub) Disconnect(clientID UUID) error

Disconnect closes a client connection and removes it from the storage.

func (*Hub) IsSubscribed

func (h *Hub) IsSubscribed(clientID UUID) bool

IsSubscribed checks does the client is subscribed to at least one channel.

func (*Hub) ListenAndServe

func (h *Hub) ListenAndServe(addr, path string) error

ListenAndServe listens on the TCP network address and handle requests on incoming connections.

func (*Hub) ListenAndServeTLS

func (h *Hub) ListenAndServeTLS(addr, path, certFile, keyFile string) error

ListenAndServe listens on the TCP network address and handle requests on incoming connections.

func (*Hub) LogDebug

func (h *Hub) LogDebug(args ...interface{})

LogDebug logs a message at level Debug.

func (*Hub) LogDebugf

func (h *Hub) LogDebugf(format string, args ...interface{})

LogDebugf is like LogDebug but allows specifying a message format.

func (*Hub) LogDebugln

func (h *Hub) LogDebugln(args ...interface{})

LogDebugln is like LogDebug but adds a new line.

func (*Hub) LogError

func (h *Hub) LogError(args ...interface{})

LogError logs a message at level Error.

func (*Hub) LogErrorf

func (h *Hub) LogErrorf(format string, args ...interface{})

LogErrorf is like LogError but allows specifying a message format.

func (*Hub) LogErrorln

func (h *Hub) LogErrorln(args ...interface{})

LogErrorln is like LogError but adds a new line.

func (*Hub) LogFatal

func (h *Hub) LogFatal(args ...interface{})

Fatal logs a message at level Fatal then the process will exit with status set to 1.

func (*Hub) LogFatalf

func (h *Hub) LogFatalf(format string, args ...interface{})

LogFatalf is like LogFatal but allows specifying a message format.

func (*Hub) LogFatalln

func (h *Hub) LogFatalln(args ...interface{})

LogFatalln is like LogFatal but adds a new line.

func (*Hub) LogInfo

func (h *Hub) LogInfo(args ...interface{})

LogInfo logs a message at level Info.

func (*Hub) LogInfof

func (h *Hub) LogInfof(format string, args ...interface{})

LogInfof is like LogInfo but allows specifying a message format.

func (*Hub) LogInfoln

func (h *Hub) LogInfoln(args ...interface{})

LogInfoln is like LogInfo but adds a new line.

func (*Hub) LogPanic

func (h *Hub) LogPanic(args ...interface{})

Panic logs a message at level Panic and panics.

func (*Hub) LogPanicf

func (h *Hub) LogPanicf(format string, args ...interface{})

LogPanicf is like LogPanic but allows specifying a message format.

func (*Hub) LogPanicln

func (h *Hub) LogPanicln(args ...interface{})

LogPanicln is like LogPanic but adds a new line.

func (*Hub) LogPrint

func (h *Hub) LogPrint(args ...interface{})

LogPrint logs a message at level Info.

func (*Hub) LogPrintf

func (h *Hub) LogPrintf(format string, args ...interface{})

LogPrintf is like LogPrint but allows specifying a message format.

func (*Hub) LogPrintln

func (h *Hub) LogPrintln(args ...interface{})

LogPrintln is like LogPrint but adds a new line.

func (*Hub) LogWarn

func (h *Hub) LogWarn(args ...interface{})

LogWarn logs a message at level Warn.

func (*Hub) LogWarnf

func (h *Hub) LogWarnf(format string, args ...interface{})

LogWarnf is like LogWarn but allows specifying a message format.

func (*Hub) LogWarnln

func (h *Hub) LogWarnln(args ...interface{})

LogWarnln is like LogWarn but adds a new line.

func (*Hub) OnConnect

func (h *Hub) OnConnect(handler ConnectHandler)

OnConnect registers a handler for client connection.

func (*Hub) OnDisconnect

func (h *Hub) OnDisconnect(handler DisconnectHandler)

OnDisconnect registers a handler for client disconnection.

func (*Hub) OnError

func (h *Hub) OnError(handler ErrorHandler)

OnError registers a handler for errors occurred while reading or writing connection.

func (*Hub) OnReceive

func (h *Hub) OnReceive(handler ReceiveHandler)

OnReceive registers a handler for incoming messages.

func (*Hub) Publish

func (h *Hub) Publish(message Message, channels ...string) (int, error)

Publish publishes a message to the channels. If channels were not specified then all clients will receive the message.

func (*Hub) Send

func (h *Hub) Send(clientID UUID, message Message) error

Send sends a message to a specific client.

func (*Hub) ServeHTTP

func (h *Hub) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServeHTTP implements http.Handler interface and responsible for connect new clients.

func (*Hub) Subscribe

func (h *Hub) Subscribe(clientID UUID, channels ...string) error

Subscribe allows to subscribe a client to specific channels. At least one channel is required.

func (*Hub) Unsubscribe

func (h *Hub) Unsubscribe(clientID UUID, channels ...string) error

Unsubscribe allows to unsubscribe a client from specific channels. If channels were not specified then the client will be unsubscribed from all channels.

type HubOptions

type HubOptions struct {
	// Time to gracefully shutdown a server
	ShutdownTimeout time.Duration

	// Enable/disable debug mode.
	IsDebug bool

	// Function execution time limit in debug mode.
	// Exceeding this time limit will cause a new warn log message.
	DebugFuncTimeLimit time.Duration
}

HubOptions represents configuration of the hub.

func NewHubOptions

func NewHubOptions() HubOptions

NewHubOptions initializes a new HubOptions. nolint: gomnd

type HubSubscriptionChannelRequired

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

HubSubscriptionChannelRequired returned when trying to subscribe with an empty channels list.

func IsHubSubscriptionChannelRequiredError

func IsHubSubscriptionChannelRequiredError(err error) (*HubSubscriptionChannelRequired, bool)

IsHubSubscriptionChannelRequiredError checks if error type is HubSubscriptionChannelRequired.

func NewHubSubscriptionChannelRequiredError

func NewHubSubscriptionChannelRequiredError() *HubSubscriptionChannelRequired

NewHubSubscriptionChannelRequiredError initializes a new HubSubscriptionChannelRequired.

func (*HubSubscriptionChannelRequired) Error

HubSubscriptionChannelRequired implements an error interface.

type IterateFunc

type IterateFunc func(client WebsocketClient) error

IterateFunc is the type of the function called for each client visited by Find.

type Logger

type Logger interface {
	Debug(args ...interface{})
	Info(args ...interface{})
	Print(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})

	Debugln(args ...interface{})
	Infoln(args ...interface{})
	Println(args ...interface{})
	Warnln(args ...interface{})
	Errorln(args ...interface{})
	Fatalln(args ...interface{})
	Panicln(args ...interface{})

	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Printf(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})
}

Logger is an interface representing the ability to log messages.

type LogrusFormatter

type LogrusFormatter uint32

LogrusFormatter enumerates possible formatters.

const (
	// LogrusFormatterText formats logs into text.
	LogrusFormatterText LogrusFormatter = iota

	// LogrusFormatterJSON formats logs into parsable JSON.
	LogrusFormatterJSON
)

type LogrusLevel

type LogrusLevel uint32

LogrusLevel enumerates possible logging levels.

const (
	LogrusLevelPanic LogrusLevel = iota
	LogrusLevelFatal
	LogrusLevelError
	LogrusLevelWarn
	LogrusLevelInfo
	LogrusLevelDebug
	LogrusLevelTrace
)

type LogrusLogger

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

LogrusLogger is an implementation of Logger.

func NewLogrusLogger

func NewLogrusLogger(options LogrusLoggerOptions) *LogrusLogger

NewLogrusLogger initializes a new LogrusLogger.

func (LogrusLogger) Debug

func (l LogrusLogger) Debug(args ...interface{})

Debug logs a message at level Debug.

func (LogrusLogger) Debugf

func (l LogrusLogger) Debugf(format string, args ...interface{})

Debugf is like LogDebug but allows specifying a message format.

func (LogrusLogger) Debugln

func (l LogrusLogger) Debugln(args ...interface{})

Debugln is like LogDebug but adds a new line.

func (LogrusLogger) Error

func (l LogrusLogger) Error(args ...interface{})

Error logs a message at level Error.

func (LogrusLogger) Errorf

func (l LogrusLogger) Errorf(format string, args ...interface{})

Errorf is like LogError but allows specifying a message format.

func (LogrusLogger) Errorln

func (l LogrusLogger) Errorln(args ...interface{})

Errorln is like LogError but adds a new line.

func (LogrusLogger) Fatal

func (l LogrusLogger) Fatal(args ...interface{})

Fatal logs a message at level Fatal then the process will exit with status set to 1.

func (LogrusLogger) Fatalf

func (l LogrusLogger) Fatalf(format string, args ...interface{})

Fatalf is like LogFatal but allows specifying a message format.

func (LogrusLogger) Fatalln

func (l LogrusLogger) Fatalln(args ...interface{})

Fatalln is like LogFatal but adds a new line.

func (LogrusLogger) Info

func (l LogrusLogger) Info(args ...interface{})

Info logs a message at level Info.

func (LogrusLogger) Infof

func (l LogrusLogger) Infof(format string, args ...interface{})

Infof is like LogInfo but allows specifying a message format.

func (LogrusLogger) Infoln

func (l LogrusLogger) Infoln(args ...interface{})

Infoln is like LogInfo but adds a new line.

func (LogrusLogger) Panic

func (l LogrusLogger) Panic(args ...interface{})

Panic logs a message at level Panic and panics.

func (LogrusLogger) Panicf

func (l LogrusLogger) Panicf(format string, args ...interface{})

Panicf is like LogPanic but allows specifying a message format.

func (LogrusLogger) Panicln

func (l LogrusLogger) Panicln(args ...interface{})

Panicln is like LogPanic but adds a new line.

func (LogrusLogger) Print

func (l LogrusLogger) Print(args ...interface{})

Print logs a message at level Info.

func (LogrusLogger) Printf

func (l LogrusLogger) Printf(format string, args ...interface{})

Printf is like LogPrint but allows specifying a message format.

func (LogrusLogger) Println

func (l LogrusLogger) Println(args ...interface{})

Println is like LogPrint but adds a new line.

func (LogrusLogger) Warn

func (l LogrusLogger) Warn(args ...interface{})

Warn logs a message at level Warn.

func (LogrusLogger) Warnf

func (l LogrusLogger) Warnf(format string, args ...interface{})

Warnf is like LogWarn but allows specifying a message format.

func (LogrusLogger) Warnln

func (l LogrusLogger) Warnln(args ...interface{})

Warnln is like LogWarn but adds a new line.

type LogrusLoggerOptions

type LogrusLoggerOptions struct {
	Level     LogrusLevel
	Formatter LogrusFormatter
	Output    io.Writer
}

LogrusLoggerOptions represents configuration of the LogrusLogger.

func NewLogrusLoggerOptions

func NewLogrusLoggerOptions() LogrusLoggerOptions

NewLogrusLoggerOptions initializes a new LogrusLoggerOptions.

type Message

type Message struct {
	Type    MessageType
	Payload []byte
}

Message represents a data type to send over a WebSocket connection.

func NewBinaryMessage

func NewBinaryMessage(payload []byte) Message

NewBinaryMessage initializes a new binary Message from bytes.

func NewBinaryMessageFromString

func NewBinaryMessageFromString(payload string) Message

NewBinaryMessageFromString initializes a new binary Message from string.

func NewPingMessage

func NewPingMessage() Message

NewPingMessage initializes a new ping Message.

func NewTextMessage

func NewTextMessage(payload []byte) Message

NewTextMessage initializes a new text Message from bytes.

func NewTextMessageFromString

func NewTextMessageFromString(payload string) Message

NewTextMessage initializes a new text Message from string.

type MessageType

type MessageType byte

MessageType enumerates possible message types.

const (
	MessageTypeText   MessageType = 1
	MessageTypeBinary MessageType = 2
	MessageTypePing   MessageType = 9
)

type ReceiveHandler

type ReceiveHandler func(clientID UUID, message Message)

ReceiveHandler called when a client reads a new message.

type SatoriUUIDGenerator

type SatoriUUIDGenerator struct{}

SatoriUUIDGenerator is an implementation of UUIDGenerator.

func (SatoriUUIDGenerator) GenerateV4

func (s SatoriUUIDGenerator) GenerateV4() UUID

GenerateV4 returns random generated UUID.

type UUID

type UUID [16]byte

UUID represents a type compliant with specification described in RFC 4122.

func (UUID) Bytes

func (u UUID) Bytes() []byte

Bytes returns bytes slice representation of UUID.

func (UUID) String

func (u UUID) String() string

String returns canonical string representation of UUID.

type UUIDGenerator

type UUIDGenerator interface {
	GenerateV4() UUID
}

UUIDGenerator generates UUID v4.

type WebsocketClient

type WebsocketClient interface {
	ID() UUID
	Connect(response http.ResponseWriter, request *http.Request) error
	OnReceive(handler ReceiveHandler)
	OnError(handler ErrorHandler)
	Send(message Message) error
	Close() error
}

WebsocketClient is an interface representing the ability to interact with WebSocket connection.

type WebsocketClientFactory

type WebsocketClientFactory interface {
	Create() WebsocketClient
}

WebsocketClientStore is an interface responsible for creating a client.

type WebsocketClientStore

type WebsocketClientStore interface {
	Get(clientID UUID) (WebsocketClient, error)
	Set(client WebsocketClient)
	Unset(clientID UUID) error
	Count(channels ...string) int
	Find(fn IterateFunc, channels ...string) error
	Channels(clientID UUID) ([]string, error)
	CountChannels(clientID UUID) (int, error)
	SetChannels(clientID UUID, channels ...string) error
	UnsetChannels(clientID UUID, channels ...string) error
}

WebsocketClientStore is an interface responsible for storing and finding the users.

type WebsocketConnection

type WebsocketConnection interface {
	Read() (Message, error)
	Write(message Message) error
	Close() error
}

WebsocketConnection represents a WebSocket connection.

type WebsocketConnectionUpgrader

type WebsocketConnectionUpgrader interface {
	Upgrade(w http.ResponseWriter, r *http.Request) (WebsocketConnection, error)
}

WebsocketConnectionUpgrader upgrades HTTP connection to the WebSocket connection.

Directories

Path Synopsis
examples
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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