wsocket

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

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

Go to latest
Published: Dec 11, 2023 License: MIT Imports: 9 Imported by: 0

README

WSocket: Golang WebSocket client/server library.

GoDoc Coverage Status

The primary goal of this library is to provide WebSocket message routing in a manner similar to conventional HTTP routing. It achieves this through the use of a message resolver. You can use a default JSON resolver to identify messages based on a specific field within the JSON content. Users can further customize their routing logic by implementing the wsocket.Resolver interface to create custom resolvers.

Features

  • JSON message resolver
  • Custom message resolvers
  • Text and binary message support
  • Middleware support
  • Context support

Usage

More examples of usage can be found in the examples directory.

// Create a new resolver that will match on the "message.type" field
// JSONResolver supports nested fields. For example "message.type" will match on {"message": {"type": "value"}}
resolver := wsocket.NewJSONResolver("message.type")
// Add a handler for the "sum-request" type
resolver.AddHandler("sum-request", handleSum)

...

// Create a new client with the resolver and disable logger
wsClient := wsocket.NewClient(context.Background(), resolver, &wsocket.NoLogger{})
// Add a middleware that will log all messages
wsClient.AddMiddleware(messageLogger)

...

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
    start := time.Now()
	
    // upgrade the connection to a websocket connection using gorilla/websocket
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Printf("Failed to upgrade connection: %v\n", err)
        return
    }
    
    // create a new connection using the client and the websocket connection
    conn := wsClient.NewConnection(c)
    <-conn.Wait()
    log.Printf("Connection closed after %f seconds", time.Since(start).Seconds())
})

...

// wsocket.Connection has a Write method that will write the message to the websocket connection
err = conn.WriteMessage(wsocket.NewTextMessage([]byte(`{"type": "sum-request", "a": 1, "b": 2}`)))
if err != nil {
    log.Printf("Failed to write message: %v\n", err)
    return
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client interface {
	AddMiddleware(middleware Middleware)
	NewConnection(conn *websocket.Conn) Connection
}

func NewClient

func NewClient(ctx context.Context, resolver Resolver, logger Logger, writeChanSize int) Client

NewClient creates a new client instance. ctx is used to cancel the client. resolver is used to resolve incoming messages. logger is used to log errors. If nil, a default logger is used. You can use NoLogger to disable logging.

type Connection

type Connection interface {
	ResponseWriter

	// Close closes the connection.
	// If the connection is already closed, an error is returned.
	Close() error

	// Wait returns a channel that is closed when the connection is closed.
	Wait() <-chan struct{}
}

type Handler

type Handler func(ctx context.Context, msg []byte, rw ResponseWriter) error

type JSONResolver

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

func NewJSONResolver

func NewJSONResolver(field string) *JSONResolver

NewJSONResolver creates a new JSONResolver instance. field is the name of the field in the JSON message that is used to resolve the handler. For example, if field is "type", the message {"type": "sum-request", "a": 1, "b": 2} is resolved to the handler registered for "sum-request". If the field is nested, use dot notation, e.g. "type.name".

func (*JSONResolver) AddHandler

func (r *JSONResolver) AddHandler(name string, handler Handler) *JSONResolver

AddHandler adds a handler for a message type. name is the value of the field that is used to resolve the handler.

func (*JSONResolver) Handle

func (r *JSONResolver) Handle(ctx context.Context, msg []byte, rw ResponseWriter) error

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

func DefaultLogger

func DefaultLogger() Logger

func NoLogger

func NoLogger() Logger

type Message

type Message struct {
	Message []byte
	// contains filtered or unexported fields
}

Message is a message that can be sent to a connection. It is recommended to use the NewTextMessage, NewBinaryMessage and NewCloseMessage functions to create a Message.

func NewBinaryMessage

func NewBinaryMessage(msg []byte) Message

func NewCloseMessage

func NewCloseMessage() Message

func NewTextMessage

func NewTextMessage(msg []byte) Message

type Middleware

type Middleware func(ctx context.Context, msg []byte) (context.Context, []byte, error)

type Resolver

type Resolver interface {
	// Handle resolves a message to a handler and returns the result of the handler.
	// If the message cannot be resolved, an error is returned.
	Handle(ctx context.Context, msg []byte, rw ResponseWriter) error
}

Resolver is used to resolve a message to a handler.

type ResponseWriter

type ResponseWriter interface {
	// WriteMessage writes a message to the connection.
	// If the message type is 0, it is set to websocket.TextMessage.
	// If the message type is not websocket.TextMessage, websocket.BinaryMessage or websocket.CloseMessage, an error is returned.
	WriteMessage(msg Message) error
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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