socketify

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2022 License: MIT Imports: 13 Imported by: 0

README

Go-Socketify

A simple WebSocket framework for Go

Install

go get -u github.com/aliforever/go-socketify

Usage

A simple app that PONG when PING

options := socketify.ServerOptions().SetAddress(":8080").SetEndpoint("/ws").IgnoreCheckOrigin()
server := socketify.NewServer(options)
go server.Listen()

for connection := range server.Connections() {
    connection.HandleUpdate("PING", socketify.NewMapper[socketify.EmptyInput](func(_ socketify.EmptyInput) {
        connection.WriteUpdate("PONG", nil)
    }))
    go connection.ProcessUpdates()
}

Run the application and send below JSON to "ws://127.0.0.1:8080/ws":

{
  "type": "PING"
}

You'll receive:

{
  "type": "PONG"
}

Conventions

Events are ought to be sent/received with following JSON format:

{
  "type": "UpdateType",
  "data": {}
}

Type is going to be your update type and data is going to be anything.

Storage

You can retrieve clients within other clients by using Socketify's client storage.

You can enable the storage by setting option EnableStorage():

options := socketify.Options().
	SetAddress(":8080").
	SetEndpoint("/ws").
	IgnoreCheckOrigin().
	EnableStorage() // <-- This LINE

Each client has a unique ID set by shortid package, you can recall using client.ID().

Clients are stored in a map with their unique ID and you can retrieve them by calling:

client.Server().Storage().GetClientByID(UniqueID)

Handlers

You can specify a handler for an updateType to each client by using:

client.HandleUpdate("UpdateType", func(message json.RawMessage) {
	// Process message
})

This way Socketify will call your registered handler if it receives any updates with UpdateType specified.

Or you can just listen on updates on your own:

go client.ProcessUpdates()
go func(c *socketify.Client) {
    for update := range c.Updates() {
        fmt.Println(update)
    }
}(client)

Note: You should always call go client.ProcessUpdates() to let a Socketify client receive updates.

Docs:

Checkout Docs Here

Documentation

Index

Constants

View Source
const (
	EncryptionTypeRsaAes encryptionMethod = "RSA/AES"
)

Variables

This section is empty.

Functions

func DataMapper added in v0.3.14

func DataMapper[T any](handler func(T, ...string) error) dataMapper[T]

func ServerOptions added in v0.3.0

func ServerOptions() *options

Types

type Client

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

func NewClient added in v0.3.0

func NewClient(address string) (*Client, error)

func (*Client) Close added in v0.1.4

func (c *Client) Close(code int, message string)

func (*Client) NextReader added in v0.3.7

func (c *Client) NextReader() (messageType int, r io.Reader, err error)

func (*Client) NextWriterBinary added in v0.3.10

func (c *Client) NextWriterBinary() (r io.Writer, err error)

func (*Client) NextWriterCloseMessage added in v0.3.12

func (c *Client) NextWriterCloseMessage() (r io.Writer, err error)

func (*Client) NextWriterText added in v0.3.10

func (c *Client) NextWriterText() (r io.Writer, err error)

func (*Client) SetOnClose added in v0.1.9

func (c *Client) SetOnClose(fn func(err error)) *Client

func (*Client) SetOnError added in v0.3.0

func (c *Client) SetOnError(fn func(err error)) *Client

func (*Client) SetRawHandler added in v0.3.0

func (c *Client) SetRawHandler(fn func(message []byte)) *Client

func (*Client) SetRawMiddleware added in v0.3.4

func (c *Client) SetRawMiddleware(fn func(message []byte)) *Client

func (*Client) SetUpdateTypeHandler added in v0.3.0

func (c *Client) SetUpdateTypeHandler(updateType string, fn func(message json.RawMessage)) *Client

func (Client) WriteBinaryBytes added in v0.2.5

func (w Client) WriteBinaryBytes(data []byte) (err error)

func (Client) WriteBinaryText added in v0.2.7

func (w Client) WriteBinaryText(data []byte) (err error)

func (Client) WriteRawUpdate added in v0.1.4

func (w Client) WriteRawUpdate(data interface{}) (err error)

func (Client) WriteText added in v0.2.5

func (w Client) WriteText(data string) (err error)

func (Client) WriteUpdate

func (w Client) WriteUpdate(updateType string, data interface{}, extra ...string) (err error)

type Connection added in v0.2.9

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

func (*Connection) Close added in v0.2.9

func (c *Connection) Close() error

func (*Connection) Errors added in v0.2.9

func (c *Connection) Errors() <-chan UpdateError

func (*Connection) GetAttribute added in v0.2.9

func (c *Connection) GetAttribute(key string) (val interface{}, exists bool)

func (*Connection) HandleRawUpdate added in v0.2.9

func (c *Connection) HandleRawUpdate(handler func(message []byte))

HandleRawUpdate registers a default handler for update Note: Add a raw handler if you don't want to follow the API convention {"type": "", "data": {}}

func (*Connection) HandleUpdate added in v0.2.9

func (c *Connection) HandleUpdate(updateType string, handler mapper)

HandleUpdate registers a default handler for updateType For the second argument you should pass your handler inside DataMapper as follows: socketify.DataMapper[T](handler) If the input is going to be empty (update.data == nil) then you can pass socketify.EmptyInput as input Care: If you use this method for an updateType, you won't receive the respected update in your listener

func (*Connection) ID added in v0.2.9

func (c *Connection) ID() string

func (*Connection) InternalUpdates added in v0.2.9

func (c *Connection) InternalUpdates() <-chan []byte

func (*Connection) NextReader added in v0.3.8

func (c *Connection) NextReader() (messageType int, r io.Reader, err error)

func (*Connection) NextWriterBinary added in v0.3.11

func (c *Connection) NextWriterBinary() (r io.Writer, err error)

func (*Connection) NextWriterCloseMessage added in v0.3.11

func (c *Connection) NextWriterCloseMessage() (r io.Writer, err error)

func (*Connection) NextWriterText added in v0.3.11

func (c *Connection) NextWriterText() (r io.Writer, err error)

func (*Connection) ProcessUpdates added in v0.2.9

func (c *Connection) ProcessUpdates() error

func (*Connection) Server added in v0.2.9

func (c *Connection) Server() *Server

func (*Connection) SetAttribute added in v0.2.9

func (c *Connection) SetAttribute(key string, val interface{})

func (*Connection) SetKeepAliveDuration added in v0.2.9

func (c *Connection) SetKeepAliveDuration(keepAlive time.Duration)

func (*Connection) SetMiddleware added in v0.2.9

func (c *Connection) SetMiddleware(middleware func(message []byte) error)

func (*Connection) SetOnClose added in v0.2.9

func (c *Connection) SetOnClose(onClose func())

func (*Connection) SetUpdateTypeMiddleware added in v0.2.9

func (c *Connection) SetUpdateTypeMiddleware(middleware func(updateType string, data json.RawMessage) error)

func (Connection) WriteBinaryBytes added in v0.2.9

func (w Connection) WriteBinaryBytes(data []byte) (err error)

func (Connection) WriteBinaryText added in v0.2.9

func (w Connection) WriteBinaryText(data []byte) (err error)

func (*Connection) WriteInternalUpdate added in v0.2.9

func (c *Connection) WriteInternalUpdate(update []byte)

func (Connection) WriteRawUpdate added in v0.2.9

func (w Connection) WriteRawUpdate(data interface{}) (err error)

func (Connection) WriteText added in v0.2.9

func (w Connection) WriteText(data string) (err error)

func (Connection) WriteUpdate added in v0.2.9

func (w Connection) WriteUpdate(updateType string, data interface{}, extra ...string) (err error)

type EmptyInput added in v0.3.14

type EmptyInput struct{}

type Logger

type Logger interface {
	Error(args ...interface{})
}

type Server added in v0.2.9

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

func NewServer added in v0.3.0

func NewServer(opts *options) (s *Server)

func (*Server) Listen added in v0.2.9

func (s *Server) Listen() (err error)

func (*Server) Server added in v0.2.9

func (s *Server) Server() (server *http.Server)

func (*Server) Storage added in v0.2.9

func (s *Server) Storage() *storage

func (*Server) UpgradeRequests added in v0.4.0

func (s *Server) UpgradeRequests() chan *UpgradeRequest

type Update

type Update struct {
	Type  string          `json:"type"`
	Data  json.RawMessage `json:"data,omitempty"`
	Extra string          `json:"extra,omitempty"`
}

type UpdateError added in v0.3.15

type UpdateError struct {
	Update []byte
	Error  error
	Extra  []string
}

type UpgradeRequest added in v0.4.0

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

func (*UpgradeRequest) Request added in v0.4.0

func (u *UpgradeRequest) Request() *http.Request

func (*UpgradeRequest) SetAttribute added in v0.4.0

func (u *UpgradeRequest) SetAttribute(key string, val interface{}) *UpgradeRequest

func (*UpgradeRequest) SetClientID added in v0.4.0

func (u *UpgradeRequest) SetClientID(clientID string) *UpgradeRequest

func (*UpgradeRequest) Upgrade added in v0.4.0

func (u *UpgradeRequest) Upgrade() (*Connection, error)

func (*UpgradeRequest) WriteResponse added in v0.4.0

func (u *UpgradeRequest) WriteResponse(statusCode int, header http.Header, response []byte) (int, error)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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