ax

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

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

Go to latest
Published: Jul 28, 2015 License: MIT Imports: 13 Imported by: 0

README

ax

Ax is a lightweight Go web toolkit for creating single page applications. It is built on the top of Gorilla WebSocket library. The design is focused on simplicity and performance.

This is not a web framework. This is a utilitarian tool to solve practical problems. There are no routing, templates, rendering, databases etc. Only a WebSocket connection between frontend and backend for message passing.

Quick start:

go get github.com/devhq-io/ax
cd  $GOPATH/src/github.com/devhq/ax
./axnew -n foo /tmp/foo
cd /tmp/foo
go build
./foo

Then navigate to http://localhost:2000

JavaScript API (frontend)

Connecting to the backend:

ax.connect(function () {
    // ... connected OK ...
});

Handling disconnects:

ax.onDisconnect(function () {
    // ... disconnected ...
});

Sending a JSON message to the backend:

ax.send('foo_msg', {foo_data: 'hello!'});

Handling JSON messages from the backend:

ax.on('foo_msg_from_backend', function (data) {
	console.log('JSON message from the backend:' + JSON.stringify(data));
});

Handling raw messages (in your custom format) from the backend:

ax.onRaw(function (data) {
	console.log('Raw message from the backend');
});

Note, if raw message handler have been set, JSON messages from the backend are ignored.

Go API (backend)

Initialization:

c := &ax.Config{
        UseTls: true, // whether the client should use 'wss://' prefix instead of 'ws://'
        ConnectionTimeout: 300, // Time (seconds) during which client's
	                        // "connection ID" cookie is active
}
ax.Setup(c)

Then you need to set up the routing and start your HTTP(S) server. See skeleton/main.go for the example.

Handling new client entered:

ax.OnEnter(func(c *ax.Client, r *http.Request) {
	log.Printf("A new client with connection id '%s'\n", c.Cid())
})

Handling client leaving:

ax.OnLeave(func(c *ax.Client) {
	log.Printf("The client with connection id '%s' has left\n", c.Cid())
})

The client has a continuous WebSocket connection with the server. When it is closed at the client, OnLeave callback is called.

The client has an unique connection ID string. It can be obtained as follows:

cid := c.Cid()

The client has a context in-memory map which can be easily used by the developer:

ax.OnEnter(func(c *ax.Client, r *http.Request) {
	c.Context["user_name"] = "John"
	c.Context["score"] = 123
}

...

score, ok := c.Context["score"].(int)
userName, ok := c.Context["user_name"].(string)

Handling JSON messages from the client's frontend:

ax.OnJson("foo_msg", func(c *ax.Client, data interface{}){
	log.Printf("'foo_msg' JSON message from client '%s': %+v\n", c.Cid(), data)
})

Handling raw messages from the client's frontend:

ax.OnRaw(func(c *ax.Client, data []byte) bool {
	log.Printf("Raw message from client '%s': %+v\n", c.Cid(), data)
	// return true if message has been handled, false otherwise
	return true
})

Sending a JSON message:

c.JsonSend("foo_msg_from_backend",
	&struct{
		UserName string `json:"user_name"`
		Score int `json:"score"`
	}{
		"John",
		123
	}
)

Sending a raw message:

c.Send([]byte("this is a raw binary message"))

Disconnecting the client (onDisconnect() will be called at the client):

c.Disconnect()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDisconnected = errors.New("Attempt to perform send/shutdown at disconnected client")
)

Functions

func OnEnter

func OnEnter(handler func(c *Client, r *http.Request))

func OnJson

func OnJson(msgtype string, handler JsonMessageHandler)

func OnLeave

func OnLeave(handler func(c *Client))

func OnPing

func OnPing(handler func(c *Client))

func OnRaw

func OnRaw(handler RawMessageHandler)

Types

type Client

type Client struct {

	// User context (available for client code)
	Context map[string]interface{}
	// contains filtered or unexported fields
}

Structure `Client` defines client contiguous connection.

func (*Client) Cid

func (c *Client) Cid() string

func (*Client) Disconnect

func (c *Client) Disconnect() error

func (*Client) JsonSend

func (c *Client) JsonSend(msgtype string, arg interface{}) error

func (*Client) Send

func (c *Client) Send(data []byte) error

type Config

type Config struct {
	UseTls            bool
	ConnectionTimeout int
}

type JsonClientMessage

type JsonClientMessage struct {
	MsgType string      `json:"type"`
	Data    interface{} `json:"data"`
}

type JsonMessageHandler

type JsonMessageHandler func(c *Client, data interface{})

type RawMessageHandler

type RawMessageHandler func(c *Client, data []byte) bool

type Router

type Router struct {
	mux.Router
}

func Setup

func Setup(c *Config) *Router

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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