organics

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

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

Go to latest
Published: Jul 27, 2021 License: BSD-3-Clause Imports: 19 Imported by: 0

README

##Organic communication between JavaScript and Go! Organics is an software library providing natural, easy, efficient, two-way communication between JavaScript enabled web browsers and Go web servers.

  • See the Wiki.
  • Check out the API.
  • go get github.com/sinni800/organics

Documentation

Overview

Organics provides two-way communication between an browser and web server.

Organics provides two-way communication between an browser and web server.

Index

Constants

This section is empty.

Variables

View Source
var (

	// Special message for when an client connection is made.
	Connect = &connect
)

Special messages for different server events, only intended to be entirely unique.

Functions

func SetDebugOutput

func SetDebugOutput(w io.Writer)

SetDebugOutput specifies an io.Writer which Organics will write debug information to.

Types

type Connection

type Connection struct {
	*Store
	// contains filtered or unexported fields
}

Connection represents an single connection to an web browser, this connection will remain for as long as the user keeps the web page open through their browser.

func (*Connection) Address

func (c *Connection) Address() string

Address returns the client address of this connection, usually for logging purposes.

Format: ip:port

func (*Connection) Dead

func (c *Connection) Dead() bool

Dead tells weather this Connection is dead or not.

func (*Connection) DeathNotify

func (c *Connection) DeathNotify() chan bool

DeathNotify returns an new channel on which true will be sent once this connection is killed.

An connection is considered killed once it's Kill() method has been called.

If this connection is dead, then this function returns nil.

func (*Connection) Kill

func (c *Connection) Kill()

Kill kills this connection as soon as possible, this function will block until the connection is dead.

If this connection is already dead, this function is no-op.

func (*Connection) Method

func (c *Connection) Method() Method

Method returns one of the predefined constant methods which represents the method in use by this connection.

func (*Connection) Request

func (c *Connection) Request(requestName interface{}, sequence ...interface{})

Request makes an request to the other end of this Connection.

If this connection is dead, or this Connection's Session is dead, this function is no-op.

The first parameter to this function is the request name, this can be any value that the json.Marshal() function will accept.

The second parameter(s) is any sequence of arguments to the request, as many as you wish, while noting these arguments must be accepted by the json.Marshal() function.

The third (and optional) argument is an function that will be called when the request has completed (I.e. has been invoked on the other end) and it will be given the response data from the request, it shoul be of the type:

func(T, T, ...)

Where T are whatever data types the function on the other end will return once invoked.

func (*Connection) Session

func (c *Connection) Session() *Session

Session returns the session object that is associated with this connection.

func (*Connection) String

func (c *Connection) String() string

String returns an string representation of this Connection.

For security reasons the string will not contain the stores data, and will instead only contain the length of the store (I.e. how many objects it contains).

type Method

type Method uint8

Method describes an single connection method.

const (
	// Describes the long polling connection method.
	LongPolling Method = iota

	// Describes the web socket connection method.
	WebSocket
)

func (Method) String

func (m Method) String() string

String returns an string formatted version of the specified method, or an empty string if the method is invalid (unknown).

For example:

WebSocket.String() would return "WebSocket"
LongPolling.String() would return "LongPolling"

type Server

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

Server is an Organics HTTP and WebSocket server, it fulfills the Handler interface defined in the net/http package.

func NewServer

func NewServer(sessionProvider SessionProvider) *Server

NewServer returns an new, and initialized Server.

func (*Server) Connections

func (s *Server) Connections() []*Connection

Connections returns all connections this Server currently has.

func (*Server) Handle

func (s *Server) Handle(requestName, requestHandler interface{})

Handle defines that when an request with the specified requestName comes in, that the requestHandler function will be invoked in order to handle the request.

The requestName parameter may be of any valid json.Marshal() type.

The requestHandler parameter must be an function, with the type specified below, where T is any valid json.Marshal() type.

func(T, T, ..., *Session) (T, T, ...)

func (*Server) Kill

func (s *Server) Kill()

Kill kills each connection currently known to the server. It is short-hand for the following code:

for _, c := range s.Connections() {
    c.Kill()
}

func (*Server) MaxBufferSize

func (s *Server) MaxBufferSize() int64

MaxBufferSize returns the maximum buffer size of this Server.

See SetMaxBufferSize() for more information.

func (*Server) OriginAccess

func (s *Server) OriginAccess(origin string) bool

OriginAccess tells weather an origin string is currently set to allow access or deny it, based on an previous call to SetOriginAccess(), if there was no previous call to SetOriginAccess for this origin string, false is returned.

Note: If an origin of "*" was previously set via SetOriginAccess("*", true), then this function will always return true.

Note: This applies to Cross-Origin Resource Sharing (CORS) and WebSocket Origin headers.

func (*Server) Origins

func (s *Server) Origins() map[string]bool

Origins returns an map of all origin's and their respective access values.

The access value will always be true. (Origins with access denied simply do not exist in the map at all).

func (*Server) PingRate

func (s *Server) PingRate() time.Duration

PingTimeout returns the ping rate of this server.

See SetPingRate() for more information about this value.

func (*Server) PingTimeout

func (s *Server) PingTimeout() time.Duration

PingTimeout returns the ping timeout.

See SetPingTimeout() for more information.

func (*Server) Provider

func (s *Server) Provider() SessionProvider

Provider returns the session provider that is in use by this server, as it was passed in originally via NewServer().

func (*Server) ServeHTTP

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

ServeHTTP fulfills the Handler interface define in the http package.

func (*Server) SessionKeySize

func (s *Server) SessionKeySize() int64

SessionKeySize returns the size of session keys.

See SetSessionKeySize() for more information.

func (*Server) SessionTimeout

func (s *Server) SessionTimeout() time.Duration

SessionTimeout returns the session timeout of this server.

See SetSessionTimeout() for more information about this value.

func (*Server) SetMaxBufferSize

func (s *Server) SetMaxBufferSize(size int64)

SetMaxBufferSize sets the maximum size in bytes that the buffer which stores an single request may be.

If an single JSON request exceeds this size, then the message will be refused, and the session killed.

Default (1MB): 1 * 1024 * 1024

func (*Server) SetOriginAccess

func (s *Server) SetOriginAccess(origin string, allowed bool)

SetOriginAccess specifies an origin string to allow access to or deny access to.

If origin is "*" it is recognized as 'all origins'.

Note: This applies to Cross-Origin Resource Sharing (CORS) and WebSocket Origin headers.

func (*Server) SetPingRate

func (s *Server) SetPingRate(t time.Duration)

SetPingRate specifies the interval duration at which the server should request long-polling clients to verify they are still connected and active.

If an client leaves open it's long-polling POST request, then after PingRate() duration, the server will ask the client to respond ASAP, the client will then have PingTimeout() duration to respond, or else it will be considered disconnected, and the connection will be killed.

This fixes an particular issue of leaving connection objects open forever, as web browsers are never required to close an HTTP connection (although most do), and some proxies might leave an connection open perminantly, causing the servers memory to fill with dead connections, and thus an crash occuring.

Default (5 minutes): 5 * time.Minute

func (*Server) SetPingTimeout

func (s *Server) SetPingTimeout(t time.Duration)

SetPingTimeout specifies an duration which will be used to determine if an client is still considered connected.

If an client leaves open it's long-polling POST request, then after PingRate() duration, the server will ask the client to respond ASAP, the client will then have PingTimeout() duration to respond, or else it will be considered disconnected, and the connection will be killed.

This fixes an particular issue of leaving connection objects open forever, as web browsers are never required to close an HTTP connection (although most do), and some proxies might leave an connection open perminantly, causing the servers memory to fill with dead connections, and thus an crash occuring.

Default (30 seconds): 30 * time.Second

func (*Server) SetSessionKeySize

func (s *Server) SetSessionKeySize(size int64)

SetSessionKeySize specifies the number of cryptographically random bytes which will be used before sha256 hash and base64 encoding, as the per-user random session key identifier.

Default: 64

func (*Server) SetSessionTimeout

func (s *Server) SetSessionTimeout(t time.Duration)

SetSessionTimeout specifies the duration in which an session's data will be monitored for changes after the session is killed.

Default (30 seconds): 30 * time.Second

type Session

type Session struct {
	*Store
	// contains filtered or unexported fields
}

Session represents an user's session, which is built up of zero to multiple different connections.

An session is considered dead once there are no more connections to represent it.

func (*Session) Connections

func (s *Session) Connections() []*Connection

Connections returns an list of all the underlying connections which represent this session.

If this session is dead, an slice of length zero is returned.

func (*Session) Dead

func (s *Session) Dead() bool

Dead tells weather this Session is dead or not. An session is considered dead once it's Kill() method has been called.

func (*Session) DeathNotify

func (s *Session) DeathNotify() chan bool

DeathNotify returns an channel on which true will be sent once this session is killed via it's Kill() method.

If the session is already dead, and channel is still returned and will still have true sent over it.

func (*Session) Kill

func (s *Session) Kill()

Kill kills this session, all connections that represent this session will be killed as well.

If this session is already dead, this function is no-op.

func (*Session) Request

func (s *Session) Request(requestName interface{}, sequence ...interface{})

Request performs an request on each connection who currently represents this session.

See Connection.Request() for more information on how request work.

func (*Session) String

func (s *Session) String() string

String returns an string representation of this Session.

For security reasons the string will not contain the stores data, and will instead only contain the length of the store (I.e. how many objects it contains).

type SessionProvider

type SessionProvider interface {
	// Save should save the store's underlying data however the provider deems
	// proper. The key is guaranteed to be unique and will be the same key that
	// is passed into Get() for retreival.
	//
	// The channel returned should have either nil or an valid error sent over
	// it to respectively signal completion, or an error saving.
	Save(sessionKey string, whatChanged string, s *Store) error

	// Load should return an previously saved store object given the unique key
	// it was saved with.
	//
	// The store object need not be the same (I.e. it can be an new pointer or
	// object all-together), as long as the underlying data is identical.
	Load(key string) *Store
}

SessionProvider is the interface that an storage provider needs to fill in order to be accepted as an valid session provider.

Conceptually, an session provider can be thought of as an thread-safe map implementation.

Session providers Set() and Get() methods must be safe to call from multiple goroutines.

type Store

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

Store is an atomic data storage, which is used both by the Connection struct and Session struct to provide session and connection based storage facilities.

func NewStore

func NewStore() *Store

NewStore returns an new intialized *Store.

func (*Store) ChangeNotify

func (s *Store) ChangeNotify() chan bool

ChangeNotify returns an channel over which true will be sent once the data inside this store has changed.

After true is sent, the channel is closed. As such, if you intend to receive notifications forever, you'll need to constantly create a new channel with an call to this function.

func (*Store) ChangeWatcher

func (s *Store) ChangeWatcher() chan string

ChangeWatcher returns an channel over which the keys of data inside this store will be sent as they are added, removed, or changed.

In order for the caller to not miss any data changes in this store, the channel will continue to have change events sent over it until an call to the RemoveWatcher() method.

func (*Store) Copy

func (s *Store) Copy() *Store

Copy returns an new 1:1 copy of this store and it's data.

The copy does not include data change notifiers returned by ChangeNotify().

func (*Store) Data

func (s *Store) Data() map[string]interface{}

Data returns an copy of this store's underlying data map.

func (*Store) Delete

func (s *Store) Delete(key string)

Delete deletes the specified key from this stores data, if there is no such key then this function is no-op.

func (*Store) Get

func (s *Store) Get(key string, defaultValue interface{}) interface{}

Get returns the specified key from this stores data, or if this store does not have the specified key then the key is set to the default value and the default value is returned.

func (*Store) GobDecode

func (s *Store) GobDecode(data []byte) error

Implements the gob decoding interface (see the encoding/gob package for more information).

func (*Store) GobEncode

func (s *Store) GobEncode() ([]byte, error)

Implements the gob encoding interface (see the encoding/gob package for more information)

func (*Store) Has

func (s *Store) Has(key string) bool

Has tells weather this Store has the specified key.

func (*Store) Keys

func (s *Store) Keys() []string

Keys returns an copy of this store's underlying data map's keys.

func (*Store) Len

func (s *Store) Len() int

Len is short hand for the following, but doesn't have to create an copy of the data map as it cannot be modified by the caller:

return len(s.Data())

func (*Store) RemoveWatcher

func (s *Store) RemoveWatcher(ch chan string)

RemoveWatcher removes the specified data watcher; it must be an channel that was returned from the ChangeWatcher() method.

See ChangeWatcher() for more information.

func (*Store) Reset

func (s *Store) Reset()

Reset resets this store such that there is absolutely no data inside of it.

func (*Store) Set

func (s *Store) Set(key string, value interface{})

Set sets the specified key to the specified value

func (*Store) String

func (s *Store) String() string

String returns an string representation of this Store

Note that this prints all data inside this store -- as such if the store may contain sensitive data (I.e. passwords, credit card numbers, etc) then you might want to never print the store for security reasons.

func (*Store) Values

func (s *Store) Values() []interface{}

Values returns an copy of this store's underlying data map's values.

Directories

Path Synopsis
examples
organics_chat
Simple chat server and client example
Simple chat server and client example
organics_hello_world
Organics simple hello world server/client example.
Organics simple hello world server/client example.
provider
filesystem
Package filesystem implements file-based session storage.
Package filesystem implements file-based session storage.
memory
Package memory implements in-memory session storage.
Package memory implements in-memory session storage.
mongo
Package mongo implements mongodb session storage.
Package mongo implements mongodb session storage.

Jump to

Keyboard shortcuts

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