sockjs_go

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2019 License: BSD-3-Clause Imports: 14 Imported by: 0

README

Go Report Card

What is SockJS?

SockJS is a JavaScript library (for browsers) that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server, with WebSockets or without. This necessitates the use of a server, which this is one version of, for GO.

SockJS-Go server library

SockJS-Go is a SockJS server library written in Go.

To use current stable version v2

go get gopkg.in/igm/sockjs-go.v2/sockjs

To use previous version v1 (DEPRECATED)

go get gopkg.in/igm/sockjs-go.v1/sockjs

To install development version of sockjs-go run:

go get github.com/igm/sockjs-go/sockjs

Versioning

SockJS-Go project adopted gopkg.in approach for versioning. SockJS-Go library details can be found here

Example

A simple echo sockjs server:

package main

import (
	"log"
	"net/http"

	"gopkg.in/igm/sockjs-go.v2/sockjs"
)

func main() {
	handler := sockjs.NewHandler("/echo", sockjs.DefaultOptions, echoHandler) 
	log.Fatal(http.ListenAndServe(":8081", handler))
}

func echoHandler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			session.Send(msg)
			continue
		}
		break
	}
}

SockJS Protocol Tests Status

SockJS defines a set of protocol tests to quarantee a server compatibility with sockjs client library and various browsers. SockJS-Go server library aims to provide full compatibility, however there are couple of tests that don't and probably will never pass due to reasons explained in table below:

Failing Test Explanation
XhrPolling.test_transport does not pass due to a feature in net/http that does not send content-type header in case of StatusNoContent response code (even if explicitly set in the code), details
WebSocket. Sockjs Go version supports RFC 6455, draft protocols hixie-76, hybi-10 are not supported
JSONEncoding As menioned in browser quirks section: "it's advisable to use only valid characters. Using invalid characters is a bit slower, and may not work with SockJS servers that have a proper Unicode support." Go lang has a proper Unicode support
RawWebsocket. The sockjs protocol tests use old WebSocket client library (hybi-10) that does not support RFC 6455 properly

WebSocket

As mentioned above sockjs-go library is compatible with RFC 6455. That means the browsers not supporting RFC 6455 are not supported properly. There are no plans to support draft versions of WebSocket protocol. The WebSocket support is based on Gorilla web toolkit implementation of WebSocket.

For detailed information about browser versions supporting RFC 6455 see this wiki page.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultOptions = Options{
	Websocket:         true,
	RawWebsocket:      false,
	JSessionID:        nil,
	SockJSURL:         "//cdnjs.cloudflare.com/ajax/libs/sockjs-client/0.3.4/sockjs.min.js",
	HeartbeatDelay:    25 * time.Second,
	DisconnectDelay:   5 * time.Second,
	ResponseLimit:     128 * 1024,
	WebsocketUpgrader: nil,
}

DefaultOptions is a convenient set of options to be used for sockjs

View Source
var (
	DefaultRequestChecker = func(req *http.Request) (error, interface{}) {
		return nil, nil
	}
)
View Source
var (
	// ErrSessionNotOpen error is used to denote session not in open state.
	// Recv() and Send() operations are not suppored if session is closed.
	ErrSessionNotOpen = errors.New("sockjs: session not in open state")
)
View Source
var WebSocketReadBufSize = 4096

WebSocketReadBufSize is a parameter that is used for WebSocket Upgrader. https://github.com/gorilla/websocket/blob/master/server.go#L230

View Source
var WebSocketWriteBufSize = 4096

WebSocketWriteBufSize is a parameter that is used for WebSocket Upgrader https://github.com/gorilla/websocket/blob/master/server.go#L230

Functions

func DefaultJSessionID

func DefaultJSessionID(rw http.ResponseWriter, req *http.Request)

DefaultJSessionID is a default behaviour function to be used in options for JSessionID if JSESSIONID is needed

func NewHandler

func NewHandler(prefix string, opts Options, handleFunc sessionHandler, checker RequestChecker) *handler

NewHandler creates new HTTP handler that conforms to the basic net/http.Handler interface. It takes path prefix, options and sockjs handler function as parameters

Types

type Options

type Options struct {
	// Transports which don't support cross-domain communication natively ('eventsource' to name one) use an iframe trick.
	// A simple page is served from the SockJS server (using its foreign domain) and is placed in an invisible iframe.
	// Code run from this iframe doesn't need to worry about cross-domain issues, as it's being run from domain local to the SockJS server.
	// This iframe also does need to load SockJS javascript client library, and this option lets you specify its url (if you're unsure,
	// point it to the latest minified SockJS client release, this is the default). You must explicitly specify this url on the server
	// side for security reasons - we don't want the possibility of running any foreign javascript within the SockJS domain (aka cross site scripting attack).
	// Also, sockjs javascript library is probably already cached by the browser - it makes sense to reuse the sockjs url you're using in normally.
	SockJSURL string
	// Most streaming transports save responses on the client side and don't free memory used by delivered messages.
	// Such transports need to be garbage-collected once in a while. `response_limit` sets a minimum number of bytes that can be send
	// over a single http streaming request before it will be closed. After that client needs to open new request.
	// Setting this value to one effectively disables streaming and will make streaming transports to behave like polling transports.
	// The default value is 128K.
	ResponseLimit uint32
	// Some load balancers don't support websockets. This option can be used to disable websockets support by the server. By default websockets are enabled.
	Websocket bool
	// This option can be used to enable raw websockets support by the server. By default raw websockets are disabled.
	RawWebsocket bool
	// Provide a custom Upgrader for Websocket connections to enable features like compression.
	// See https://godoc.org/github.com/gorilla/websocket#Upgrader for more details.
	WebsocketUpgrader *websocket.Upgrader
	// WebsocketWriteTimeout is a custom write timeout for Websocket underlying network connection.
	// A zero value means writes will not time out.
	WebsocketWriteTimeout time.Duration
	// In order to keep proxies and load balancers from closing long running http requests we need to pretend that the connection is active
	// and send a heartbeat packet once in a while. This setting controls how often this is done.
	// By default a heartbeat packet is sent every 25 seconds.
	HeartbeatDelay time.Duration
	// The server closes a session when a client receiving connection have not been seen for a while.
	// This delay is configured by this setting.
	// By default the session is closed when a receiving connection wasn't seen for 5 seconds.
	DisconnectDelay time.Duration
	// Some hosting providers enable sticky sessions only to requests that have JSessionID cookie set.
	// This setting controls if the server should set this cookie to a dummy value.
	// By default setting JSessionID cookie is disabled. More sophisticated behaviour can be achieved by supplying a function.
	JSessionID func(http.ResponseWriter, *http.Request)
	// CORS origin to be set on outgoing responses. If set to the empty string, it will default to the
	// incoming `Origin` header, or "*" if the Origin header isn't set.
	Origin string
	// CheckOrigin allows to dynamically decide whether server should set CORS
	// headers or not in case of XHR requests. When true returned CORS will be
	// configured with allowed origin equal to incoming `Origin` header, or "*"
	// if the request Origin header isn't set. When false returned CORS headers
	// won't be set at all. If this function is nil then Origin option above will
	// be taken into account.
	CheckOrigin func(*http.Request) bool
}

Options type is used for defining various sockjs options

type RequestChecker

type RequestChecker func(req *http.Request) (error, interface{})

type Session

type Session interface {
	// Id returns a session id
	ID() string
	// Request returns the first http request
	Request() *http.Request
	// Recv reads one text frame from session
	Recv() (string, error)
	// Send sends one text frame to session
	Send(string) error
	// Close closes the session with provided code and reason.
	Close(status uint32, reason string) error
	//Gets the state of the session. SessionOpening/SessionActive/SessionClosing/SessionClosed;
	GetSessionState() SessionState
}

Session represents a connection between server and client.

type SessionState

type SessionState uint32

SessionState defines the current state of the session

const (
	// brand new session, need to send "h" to receiver
	SessionOpening SessionState = iota
	// active session
	SessionActive
	// session being closed, sending "closeFrame" to receivers
	SessionClosing
	// closed session, no activity at all, should be removed from handler completely and not reused
	SessionClosed
)

Jump to

Keyboard shortcuts

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