webrocket

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2011 License: BSD-3-Clause Imports: 4 Imported by: 0

README

Rocket - Advanced WebSocket server

Rocket is very fast and reliable WebSockets server written in Go language! Package contains also the webrocket library, which provides highly extensible backend, eg. for defining your own protocols (see Hacking section for details).

History and motivation

Some time ago i wrote first version of Rocket server in Ruby at top of EventMachine and EM-Websocket libs. This proof of concept version worked fine and done his job properly so i din't touched anything... until i found perfect platform to reimplement it! Go language with its concurrency model powered by goroutines and channels, and with amazing standard library impressed me and gave opportunity to write much faster, nicer and more stable Rocket implementation.

Btw. Last time i was so impressed by language and it's standard library when i wrote my first Ruby application (6 years ago?)!

Installation

First of all, i predict you don't have Go installed... Follow this installation guide and get the newest version of the compiler. Rocket uses some of unreleased websocket's stuff, so remember to clone the head version:

$ hg clone https://go.googlecode.com/hg/ go

Go is active actively developed, so it's good idea is to use head version and update it regullary.

Once you install the Go compiler, building rocket is very easy. First, clone the repo:

$ git clone git://github.com/nu7hatch/webrocket.git
$ cd webrocket

Build and install the webrocket library:

$ make && make install

Finally, build rocket command line tool:

$ cd server
$ make

If everything will go fine, then you will find the ./rocket binary in current directory.

Usage

Server is quite easy to configure and run. The only thing you have to do is to create your own configuration based on the versioned example.json file.

$ cp example.json my.json
$ # edit configuration file...
$ rocket my.json

By default rocket listens on port 9772 on localhost. You can change it in your configuration or by setting proper flags. Use rocket --help to check available flags and options.

Protocol

By default, Rocket implements simple JSON protocol for pub-sub channels. All following actions, when successfully performed, should return:

{"ok": true}

Otherwise, when error encountered, then response message has following format:

{"err": "error-code"}
Authentication
{"auth": {"access": "access-type", "secret": "secret-key"}}
  • secret - key for specified access type
  • access - can be either read-only or read-write

Error responses:

  • invalid_credentials - obviously, returned when given secret is invalid
Subscribing
{"subscribe": {"channel": "channel-name"}}
  • channel - name of channel you want to (un)subscribe, not existing channels are created automatically

Error responses:

  • access_denied - returned when current session is not authenticated for reading
  • invalid_channel_name - returned when given channel name is invalid
Unsubscribing
{"unsubscribe": {"channel": "channel-name"}}
Publishing
{"publish": {"event": "event-name", "channel": "channel-name", "data": {"foo": "bar"}}}
  • event - communication is event oriented, so each message needs to specify which event triggers it
  • channel - channel have to exist
  • data - published data

Error responses:

  • access_denied - returned when current session is not authenticated for writing
  • invalid_data - returned when published message has invalid format
  • invalid_channel - returned when destination channel doesn't exist
Closing session
{"logout": true}
Safe disconnecting
{"disconnect": true}

Hacking

TODO...

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Copyright (c) 2011 Chris Kowalik (nu7hatch). See LICENSE for details.

Documentation

Overview

Copyright 2011 Chris Kowalik (nu7hatch). All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Package webrocket implements advanced WebSocket server with custom protocols support.

Index

Constants

View Source
const (
	ReadOnlyAccess  = "read-only"
	ReadWriteAccess = "read-write"
)

Access control constants.

Variables

View Source
var AccessCodes map[string]int = map[string]int{
	ReadOnlyAccess:  1,
	ReadWriteAccess: 2,
}

Access control defaults.

Functions

func NewHandler

func NewHandler(codec websocket.Codec) *handler

Creates new handler based on specified websocket's codec. Here's an trivial example:

server := webrocket.NewServer("localhost:8080")
handler := webrocket.NewHandler(websocket.JSON)
server.Handle("/echo", handler)
server.ListenAndServe()

func NewJSONHandler

func NewJSONHandler() *handler

Creates new handler basd on the default JSON protocol.

Types

type Credentials added in v0.2.0

type Credentials struct {
	ReadOnly  string
	ReadWrite string
}

Storage for credentials setup.

type Data added in v0.2.0

type Data map[string]interface{}

Data is an general structure for all received event messages.

type Handler

type Handler interface {
	Register(s *Server, id interface{}) (websocket.Handler, os.Error)
}

Handler handlers all incoming requestes using defined protocol. Handler also manages all registered channels.

Trivial custom handler:

type MyHandler struct {
    channels map[string]
}

func (*h MyHandler) Register(id interface{}) {
    // initialize your handler here...
}

type Payload added in v0.2.0

type Payload map[string]interface{}

Payload is an general strucutre for all sent event messages.

Simple examples how to create new event message:

Payload SimpleMessage  = Payload("hello": "world")
Payload ComplexMessage = Payload("hello": Data{"foo": "bar"})
var (
	Ok                 Payload = Payload{"ok": true}
	InvalidData        Payload = Payload{"err": "invalid_data"}
	InvalidCredentials Payload = Payload{"err": "invalid_credentials"}
	InvalidChannelName Payload = Payload{"err": "invalid_channel_name"}
	InvalidChannel     Payload = Payload{"err": "invalid_channel"}
	AccessDenied       Payload = Payload{"err": "access_denied"}
)

Predefined payloads.

func (*Payload) Data added in v0.2.0

func (p *Payload) Data() (*Data, os.Error)

Returns data contained by this payload.

func (*Payload) Event added in v0.2.0

func (p *Payload) Event() (string, os.Error)

Returns name of event represented by this payload.

type Server

type Server struct {
	http.Server
	Log *log.Logger
	// contains filtered or unexported fields
}

Server defines parameters for running an WebSocket server.

func NewServer

func NewServer(addr string) *Server

Creates new rocket's server bound to specified addr. A Trivial example server:

package main

import "rocket"

func main() {
     s := rocket.NewServer("ws://localhost:8080")
     s.Handle("/echo", rocket.NewJSONHandler())
     s.ListenAndServe()
}

func (*Server) Handle

func (s *Server) Handle(path string, h Handler)

Registers payload handler under specified path. Handler have to implement communication protocol callbacks.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() os.Error

Listens on the TCP network address srv.Addr and handles requests on incoming websocket connections.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) os.Error

Listens on the TCP network address srv.Addr and handles requests on incoming TLS websocket connections.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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