webrpc

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

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

Go to latest
Published: Mar 7, 2018 License: ISC Imports: 11 Imported by: 1

README

godoc.org Build Status codecov.io

Go-WebRPC

Go-WebRPC is an RPC-style communication library providing a thin abstraction over WebSockets.

Getting Started

WebRPC is a library. To make use of it, you need to write software that imports it.

To make it easier to get started, a full demo is included that can be used with Docker Compose.

Prerequisites

Go-WebRPC is built in the Go programming language. If you are new to Go, you will need to install Go.

You may want Docker in order to easily test the demo app, though it is not required to use go-webrpc or the demo app.

Acquiring

Next, you'll want to go get go-webrpc, like so:

go get github.com/Benzinga/go-webrpc

If your $GOPATH is configured, and git is setup to know your credentials, in a few moments the command should complete with no output. The repository will exist under $GOPATH/src/github.com/Benzinga/go-webrpc. It cannot be moved from this location.

Hint: If you've never used Go before, your $GOPATH will be under the go folder of your user directory.

Demo

In order to run the demo app, you'll need to change into the example/chat directory. Then, run docker-compose up.

cd example/chat
docker-compose up

Then, in a browser, visit http://localhost:1234. You should be able to chat with yourself.

Server: Code Explanation

The server code is fairly simple, weighing around 40 lines of code.

First, the server is instantiated.

    server := webrpc.NewServer()

Next, the OnConnect handler is set. This handler handles when a WebRPC client connects, and is similar to ServeHTTP.

    server.OnConnect(func(c *webrpc.Conn) {
        ...
    })

In the OnConnect handler, we use the user's address as a sort of username.

    server.OnConnect(func(c *webrpc.Conn) {
        user := c.Addr().String()

        ...
    })

We define a few helper functions. These deal with sending messages to the client.

    server.OnConnect(func(c *webrpc.Conn) {
        ...

        join := func(ch string) {
            c.Join(ch)
            server.Broadcast(ch, "join", time.Now(), user, ch)
        }

        part := func(ch string) {
            server.Broadcast(ch, "part", time.Now(), user, ch)
            c.Leave(ch)
        }

        msg := func(ch string, msg string) {
            server.Broadcast(ch, "msg", time.Now(), user, msg)
        }

        ...
    })

To conclude our OnConnect handler, we do some things upon connecting as well as register a simple disconnect handler.

    server.OnConnect(func(c *webrpc.Conn) {
        ...

        c.On("msg", msg)
        join("#welcome")
        c.OnClose(func() {
            part("#welcome")
        })
    })

Finally, we start an HTTP server with our WebRPC setup.

    http.ListenAndServe(":4321", server)
Client

The client is written in JavaScript and uses webrpc.js. This is out of scope for this README, but the code is in the example/chat/client folder of the repository.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadArgLen   = errors.New("invalid number of arguments")
	ErrBadDispatch = errors.New("type mismatch")
	ErrNoData      = errors.New("no data")
	ErrNotFunc     = errors.New("not a function")
	ErrNilFunc     = errors.New("nil function")
)

Common handler errors.

View Source
var (
	ErrNotInChan = errors.New("not in channel")
)

Common handler errors.

Functions

This section is empty.

Types

type Client

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

Client holds an RPC client connection.

func Dial

func Dial(uri string) (*Client, error)

Dial connects to an RPC server.

func (*Client) Close

func (c *Client) Close() error

Close shuts down a connection.

func (*Client) Dispatch

func (c *Client) Dispatch()

Dispatch runs a dispatch loop.

func (*Client) Emit

func (c *Client) Emit(name string, args ...interface{}) error

Emit calls a Socket.io function.

func (*Client) NextMessage

func (c *Client) NextMessage() Message

NextMessage gets the next message.

type Config

type Config struct {
	ReadBufferSize, WriteBufferSize int
	EnableCompression               bool
}

Config specifies a configuration for the server.

type Conn

type Conn struct {
	EventHandler
	// contains filtered or unexported fields
}

Conn represents an RPC connection.

func (*Conn) Addr

func (c *Conn) Addr() net.Addr

Addr returns the remote address of the underlying connection.

func (*Conn) Broadcast

func (c *Conn) Broadcast(chname, name string, args ...interface{}) error

Broadcast sends an event to a channel. This function fails if the user is not in the channel and returns ErrNotInChan. Note that this method doesn't send the event back to the user who sent it; for that, use Server.Broadcast instead.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the underlying connection.

func (*Conn) Emit

func (c *Conn) Emit(name string, args ...interface{}) (err error)

Emit sends an event to the client.

func (*Conn) Join

func (c *Conn) Join(chname string)

Join adds the user to a channel.

func (*Conn) Leave

func (c *Conn) Leave(chname string)

Leave removes the user from a channel.

func (*Conn) OnClose

func (c *Conn) OnClose(handler func())

OnClose sets the close handler for a socket.

func (*Conn) OnError

func (c *Conn) OnError(handler func(error))

OnError sets the error handler for a socket.

type EventHandler

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

EventHandler provides a basic event handling system.

func (*EventHandler) On

func (c *EventHandler) On(name string, fn interface{})

On connects a function to an event handler.

type Message

type Message struct {
	Type MessageType       `json:"type"`
	Ack  int               `json:"ack,omitempty"`
	Name string            `json:"name,omitempty"`
	Data []json.RawMessage `json:"data,omitempty"`
}

Message represents a raw RPC message.

func NewEvent

func NewEvent(name string, args ...interface{}) (Message, error)

NewEvent creates a new event message.

func NewReply

func NewReply(ack int, name string, args ...interface{}) (Message, error)

NewReply creates a new reply message.

func (*Message) SetData

func (m *Message) SetData(args ...interface{}) error

SetData sets the data to the provided arguments, returning an error if the data could not be marshalled.

type MessageSender

type MessageSender interface {
	// contains filtered or unexported methods
}

MessageSender represents classes that can send Messages.

type MessageType

type MessageType int

MessageType represents the kind of low-level message being received.

const (
	Init  MessageType = 0
	Event MessageType = 1
	Reply MessageType = 2
	Ping  MessageType = 3
	Pong  MessageType = 4
)

This is an enumeration of possible event types.

type Server

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

Server implements an RPC server.

func NewServer

func NewServer() *Server

NewServer creates a new server instance.

func NewServerWithConfig

func NewServerWithConfig(c Config) *Server

NewServerWithConfig creates a new server with config.

func (*Server) Broadcast

func (s *Server) Broadcast(chname, name string, args ...interface{}) error

Broadcast sends a message on a given channel.

func (*Server) OnConnect

func (s *Server) OnConnect(handler func(c *Conn))

OnConnect sets the connection handler for this server.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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