pts

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2023 License: MIT Imports: 7 Imported by: 3

README


Go (Pneumatic) Tube System

Run Tests Go Report Card codecov

Go-PTS is a flexible package for managing Pub-Sub over WebSockets in Go. It offers a rest-style syntax and easily integrates with various websocket and http frameworks.

Installation

Installing the main library

  1. Get the go-pts package using the following command:
go get github.com/mono424/go-pts

Using connectors

To use go-pts with a specific websocket library, you need to install the corresponding connector.

go get github.com/mono424/go-pts-gorilla-connector

Then, you can import them in your code like this:

import (
  "github.com/mono424/go-pts"
  ptsc_gorilla "github.com/mono424/go-pts-gorilla-connector"
)

Client Libraries

For client-side integration, you can use one of the following client libraries:

Language URL
JavaScript go-pts-client-js
Dart go-pts-client-dart

Connectors

For server-side integration with WebSocket libraries, you can use one of the following connectors:

WebSocket Library URL
Gorilla WebSocket go-pts-gorilla-connector
Melody go-pts-melody-connector

Getting Started

  1. Create a new TubeSystem
tubeSystem := pts.New(ptsc_gorilla.NewConnector(
  websocket.Upgrader{},
  func(err *pts.Error) {
    println(err.Description)
  },
))
  1. Register Channels
tubeSystem.RegisterChannel("/stream/:streamId", pts.ChannelHandlers{
  OnSubscribe: func(s *pts.Context) {
    println("Client joined: " + s.FullPath)
  },
  OnMessage: func(s *pts.Context, message *pts.Message) {
    println("New Message on " + s.FullPath + ": " + string(message.Payload))
  },
  OnUnsubscribe: func(s *pts.Context) {
    println("Client left: " + s.FullPath)
  },
})
  1. Provide a connect route
r.GET("/connect", func(c *gin.Context) {
  properties := make(map[string]interface{}, 1)
  properties["ctx"] = c

  if err := tubeSystem.HandleRequest(c.Writer, c.Request, properties); err != nil {
    println("Something went wrong while handling a Socket request")
  }
})
  1. Connect from a frontend lib
const client = new GoPTSClient({ url: socketUrl, debugging: true })
client.subscribeChannel("test", console.log);
client.send("test", { payload: { foo: "bar" } })

Examples

To get a quick overview of how to use Go-PTS, check out the examples folder.

Documentation

Index

Constants

View Source
const (
	ErrorInvalidMessage       = iota // ErrorInvalidMessage if an incoming message could not be parsed
	ErrorUnknownType                 // ErrorUnknownType if a message with an unknown type is received
	ErrorUnknownChannel              // ErrorUnknownChannel if a message to an unknown channel is received or sent
	ErrorClientNotSubscribed         // ErrorClientNotSubscribed if a message is sent through a channel that is not subscribed by the client
	ErrorSendingErrorFailed          // ErrorSendingErrorFailed if a error message could not be send to a client
	ErrorSendingMessageFailed        // ErrorSendingMessageFailed if a message could not be sent to a client
)
View Source
const (
	MessageTypeSubscribe      = "subscribe"
	MessageTypeUnsubscribe    = "unsubscribe"
	MessageTypeChannelMessage = "message"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BroadcastSendResult added in v0.0.6

type BroadcastSendResult struct {
	Skipped bool
	Context *Context
	Err     *Error
}

type Channel

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

Channel describes a room, websocket users can subscribe and sent messages to.

func (*Channel) Broadcast added in v0.0.6

func (c *Channel) Broadcast(fullPath string, payload []byte, options *ChannelBroadcastOptions) *ChannelBroadcastResult

func (*Channel) FindContext

func (c *Channel) FindContext(clientId string, path string) (*Context, bool)

func (*Channel) GetAllSubscribers added in v0.0.3

func (c *Channel) GetAllSubscribers() []*Context

GetAllSubscribers returns all subscribers

func (*Channel) GetSubscribers added in v0.0.3

func (c *Channel) GetSubscribers(path string) []*Context

GetSubscribers returns subscribers for the given path

func (*Channel) HandleMessage

func (c *Channel) HandleMessage(client *Client, message *Message)

HandleMessage executes the channels OnMessage method if it exists.

func (*Channel) IsSubscribed

func (c *Channel) IsSubscribed(clientId string, path string) bool

IsSubscribed returns true if the client is connected to the channel

func (*Channel) PathMatches

func (c *Channel) PathMatches(path string) (bool, map[string]string)

PathMatches returns true and the params of the channel subscription if the path matches the path of the Channel.

func (*Channel) Subscribe

func (c *Channel) Subscribe(context *Context)

Subscribe executes the Channels middlewares and(if successful) adds the user to the Channel and executes the channels OnSubscribe handler.

func (*Channel) Unsubscribe

func (c *Channel) Unsubscribe(clientId string, path string) bool

Unsubscribe removes the client from the channel and executes the OnUnsubscribe handler

func (*Channel) UnsubscribeAllPaths

func (c *Channel) UnsubscribeAllPaths(clientId string) bool

UnsubscribeAllPaths unsubscribes a client from all paths of the channel they are connected to.

type ChannelBroadcastOptions added in v0.0.6

type ChannelBroadcastOptions struct {
	SkipClientIds []string
}

type ChannelBroadcastResult added in v0.0.6

type ChannelBroadcastResult struct {
	HasErrors bool
	Results   []*BroadcastSendResult
}

type ChannelHandlers

type ChannelHandlers struct {
	OnSubscribe             EventHandlerFunc
	OnUnsubscribe           EventHandlerFunc
	OnMessage               MessageHandlerFunc
	SubscriptionMiddlewares []SubscriptionMiddleware
}

ChannelHandlers contains all handler functions for various events in the Channel.

type ChannelStore

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

ChannelStore stores pointers to all Channels

func (*ChannelStore) Get

func (s *ChannelStore) Get(path string) (bool, *Channel, map[string]string)

Get finds a channel with a matching path.

func (*ChannelStore) GetByExactPath added in v0.0.3

func (s *ChannelStore) GetByExactPath(path string) (bool, *Channel)

GetByExactPath finds a channel by its exact path name.

func (*ChannelStore) OnMessage

func (s *ChannelStore) OnMessage(client *Client, message *Message)

func (*ChannelStore) Register

func (s *ChannelStore) Register(path string, handlers ChannelHandlers) *Channel

func (*ChannelStore) Subscribe

func (s *ChannelStore) Subscribe(client *Client, channelPath string) bool

func (*ChannelStore) Unsubscribe

func (s *ChannelStore) Unsubscribe(clientId string, channelPath string) bool

func (*ChannelStore) UnsubscribeAll

func (s *ChannelStore) UnsubscribeAll(clientId string)

type ChannelSubscribers

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

func (*ChannelSubscribers) Add

func (subs *ChannelSubscribers) Add(context *Context)

func (*ChannelSubscribers) GetAll added in v0.0.3

func (subs *ChannelSubscribers) GetAll() []*Context

func (*ChannelSubscribers) GetAllForPath added in v0.0.3

func (subs *ChannelSubscribers) GetAllForPath(path string) []*Context

func (*ChannelSubscribers) GetContext

func (subs *ChannelSubscribers) GetContext(clientId string, path string) (*Context, bool)

func (*ChannelSubscribers) IsSubscribed

func (subs *ChannelSubscribers) IsSubscribed(clientId string, path string) bool

func (*ChannelSubscribers) Remove

func (subs *ChannelSubscribers) Remove(clientId string, path string)

func (*ChannelSubscribers) RemoveAllPaths

func (subs *ChannelSubscribers) RemoveAllPaths(clientId string) []*Context

type Client

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

func NewClient

func NewClient(sendMessage MessageSendFunc, properties map[string]interface{}) *Client

func (*Client) Get

func (client *Client) Get(key string) (value interface{}, exists bool)

func (*Client) MustGet added in v0.0.5

func (client *Client) MustGet(key string) interface{}

func (*Client) Send

func (client *Client) Send(message []byte) error

func (*Client) Set

func (client *Client) Set(key string, value interface{})

type ClientStore

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

func (*ClientStore) Exists

func (c *ClientStore) Exists(id string) bool

func (*ClientStore) Get

func (c *ClientStore) Get(id string) *Client

func (*ClientStore) Join

func (c *ClientStore) Join(client *Client)

func (*ClientStore) NextId

func (c *ClientStore) NextId() string

func (*ClientStore) Remove

func (c *ClientStore) Remove(id string)

type ConnectHookFunc

type ConnectHookFunc func(*Client)

type Connector

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

func NewConnector

func NewConnector(requestHandler RequestHandlerFunc, errorHandler ErrorHandlerFunc) *Connector

func (*Connector) Join

func (c *Connector) Join(sendMessage MessageSendFunc, properties map[string]interface{}) *Client

Join To be triggered if a client connects via ws

func (*Connector) Leave

func (c *Connector) Leave(clientId string)

func (*Connector) Message

func (c *Connector) Message(clientId string, data []byte)

type Context

type Context struct {
	Client   *Client
	FullPath string
	Channel  *Channel
	// contains filtered or unexported fields
}

func (*Context) Broadcast added in v0.0.6

func (context *Context) Broadcast(payload []byte, options *ContextBroadcastOptions) *ChannelBroadcastResult

func (*Context) Get

func (context *Context) Get(key string) (value interface{}, exists bool)

func (*Context) MustGet added in v0.0.5

func (context *Context) MustGet(key string) interface{}

func (*Context) Param

func (context *Context) Param(key string) string

func (*Context) Send

func (context *Context) Send(payload []byte) *Error

func (*Context) SendError

func (context *Context) SendError(error *Error) *Error

func (*Context) Set

func (context *Context) Set(key string, value interface{})

func (*Context) SetParams

func (context *Context) SetParams(params map[string]string)

type ContextBroadcastOptions added in v0.0.6

type ContextBroadcastOptions struct {
	ExcludeContextOwner bool
}

type DisconnectHookFunc

type DisconnectHookFunc func(*Client)

type Error

type Error struct {
	Context     *Context `json:"-"`
	Code        int      `json:"code"`
	Description string   `json:"description"`
	Raw         error    `json:"-"`
}

func NewError

func NewError(context *Context, code int, description string, err error) *Error

type ErrorHandlerFunc

type ErrorHandlerFunc func(*Error)

type EventHandlerFunc

type EventHandlerFunc func(s *Context)

EventHandlerFunc is a function that is executed when subscribing or unsubscribing to the Channel.

type Hooks

type Hooks struct {
	OnConnect    ConnectHookFunc
	OnDisconnect DisconnectHookFunc
	OnMessage    MessageHookFunc
}

type Message

type Message struct {
	Type    string          `json:"type"`
	Channel string          `json:"channel"`
	Payload json.RawMessage `json:"payload"`
}

type MessageHandlerFunc

type MessageHandlerFunc func(s *Context, message *Message)

MessageHandlerFunc is a function that executes when a message is sent to the Channel.

type MessageHookFunc

type MessageHookFunc func(*Client, []byte)

type MessageSendFunc

type MessageSendFunc func(message []byte) error

type RequestHandlerFunc

type RequestHandlerFunc func(writer http.ResponseWriter, request *http.Request, properties map[string]interface{}) error

type SubscriptionMiddleware

type SubscriptionMiddleware func(s *Context) *Error

SubscriptionMiddleware is a function that is executed when a client connects to a Channel. If the middleware returns a non nil Error, the subscription won't be finished.

type TubeSystem

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

func New

func New(connector *Connector) *TubeSystem

New Creates a new TubeSystem instance

func (*TubeSystem) GetChannel added in v0.0.3

func (r *TubeSystem) GetChannel(channelPath string) (bool, *Channel)

GetChannel returns a registered channel for an exact channel path.

func (*TubeSystem) HandleRequest

func (r *TubeSystem) HandleRequest(writer http.ResponseWriter, request *http.Request, properties map[string]interface{}) error

HandleRequest handles a new websocket request, adds the properties to the new client

func (*TubeSystem) IsConnected

func (r *TubeSystem) IsConnected(clientId string) bool

func (*TubeSystem) IsSubscribed

func (r *TubeSystem) IsSubscribed(channelPath string, clientId string) bool

IsSubscribed checks whether a client is subscribed to a certain channelPath or not

func (*TubeSystem) RegisterChannel

func (r *TubeSystem) RegisterChannel(channelName string, handlers ChannelHandlers) *Channel

RegisterChannel registers a new channel

func (*TubeSystem) Send

func (r *TubeSystem) Send(channelPath string, clientId string, payload []byte) *Error

Directories

Path Synopsis
examples
echo module

Jump to

Keyboard shortcuts

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