neptulon

package module
v0.0.0-...-1397d36 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2016 License: MIT Imports: 19 Imported by: 12

README

Neptulon

Build Status GoDoc

Neptulon is a bidirectional RPC framework with middleware support. Communication protocol is JSON-RPC over WebSockets which is full-duplex bidirectional.

Neptulon framework is only about 400 lines of code, which makes it easy to fork, specialize, and maintain for specific purposes, if you need to.

Getting Started

Following is a server for echoing all incoming messages as is:

s := neptulon.NewServer("127.0.0.1:3000")
s.MiddlewareFunc(middleware.Echo)
s.ListenAndServe()

Following is a client connection to the above server. You can also use WebSocket Test Page from your browser to connect to the server.

c, _ := neptulon.NewConn()
c.Connect("ws://127.0.0.1:3000")
c.SendRequest("echo", map[string]string{"message": "Hello!"}, func(ctx *neptulon.ResCtx) error {
	var msg interface{}
	err := ctx.Result(&msg)
	fmt.Println("Server sent:", msg)
	return err
})

For a more comprehensive example, see example_test.go file.

Middleware

Both the Server and client Conn types have the same middleware handler signature: Middleware(func(ctx *ReqCtx) error). Since both the server and the client can send request messages to each other, you can use the same set of middleware to for both, to handle the incoming requests.

See middleware package to get a list of all bundled middleware.

Client Libraries

You can connect to your Neptulon server using any programming language that has WebSocket + JSON libraries. For convenience and for reference, following client modules are provided nonetheless:

  • Go: Bundled conn.go file.
  • Java: Package client-java. Uses OkHttp for WebSockets and GSON for JSON serialization.

Users

Titan mobile messaging app server is written entirely using the Neptulon framework. You can visit its repo to see a complete use case of Neptulon framework.

Testing

All the tests can be executed with GORACE="halt_on_error=1" go test -race -cover ./... command. Optionally you can add -v flag to observe all connection logs.

License

MIT

Documentation

Overview

Package neptulon is a RPC framework with middleware support.

Example

Example demonstrating the Neptulon server.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/neptulon/neptulon"
)

const debug = false

// Example demonstrating the Neptulon server.
func main() {
	type SampleMsg struct {
		Message string `json:"message"`
	}

	// start the server and echo incoming messages back to the sender
	s := neptulon.NewServer("127.0.0.1:3000")
	s.MiddlewareFunc(func(ctx *neptulon.ReqCtx) error {
		var msg SampleMsg
		if err := ctx.Params(&msg); err != nil {
			return err
		}
		ctx.Res = msg
		return ctx.Next()
	})
	go s.ListenAndServe()
	defer s.Close()

	time.Sleep(time.Millisecond * 50) // let server goroutine to warm up

	// connect to the server and send a message
	c, err := neptulon.NewConn()
	if err != nil {
		log.Fatal(err)
	}
	if err := c.Connect("ws://127.0.0.1:3000"); err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	_, err = c.SendRequest("echo", SampleMsg{Message: "Hello!"}, func(ctx *neptulon.ResCtx) error {
		var msg SampleMsg
		if err := ctx.Result(&msg); err != nil {
			return err
		}
		fmt.Println("Server says:", msg.Message)
		return nil
	})

	if err != nil {
		log.Fatal(err)
	}

	time.Sleep(time.Millisecond * 50) // wait to get an answer

}
Output:

Server says: Hello!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Conn

type Conn struct {
	ID      string     // Randomly generated unique client connection ID.
	Session *cmap.CMap // Thread-safe data store for storing arbitrary data for this connection session.
	// contains filtered or unexported fields
}

Conn is a client connection.

func NewConn

func NewConn() (*Conn, error)

NewConn creates a new Conn object.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) Connect

func (c *Conn) Connect(addr string) error

Connect connects to the given WebSocket server. addr should be formatted as ws://host:port -or- wss://host:port (i.e. ws://127.0.0.1:3000 -or- wss://localhost:3000)

func (*Conn) DisconnHandler

func (c *Conn) DisconnHandler(handler func(c *Conn))

DisconnHandler registers a function to handle disconnection event.

func (*Conn) Middleware

func (c *Conn) Middleware(middleware ...Middleware)

Middleware registers middleware to handle incoming request messages.

func (*Conn) MiddlewareFunc

func (c *Conn) MiddlewareFunc(middleware ...func(ctx *ReqCtx) error)

MiddlewareFunc registers middleware function to handle incoming request messages.

func (*Conn) RemoteAddr

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

RemoteAddr returns the remote network address.

func (*Conn) SendRequest

func (c *Conn) SendRequest(method string, params interface{}, resHandler func(res *ResCtx) error) (reqID string, err error)

SendRequest sends a JSON-RPC request through the connection with an auto generated request ID. resHandler is called when a response is returned.

func (*Conn) SendRequestArr

func (c *Conn) SendRequestArr(method string, resHandler func(res *ResCtx) error, params ...interface{}) (reqID string, err error)

SendRequestArr sends a JSON-RPC request through the connection, with array params and auto generated request ID. resHandler is called when a response is returned.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(seconds int)

SetDeadline set the read/write deadlines for the connection, in seconds. Default value for read/write deadline is 300 seconds.

func (*Conn) Wait

func (c *Conn) Wait(timeout int) error

Wait waits for all message/connection handler goroutines to exit. Returns error if wait timeouts (in seconds).

type Middleware

type Middleware interface {
	Middleware(ctx *ReqCtx) error
}

Middleware is the type definition for Neptulon middleware.

type ReqCtx

type ReqCtx struct {
	Conn    *Conn      // Client connection.
	Session *cmap.CMap // Session is a data store for storing arbitrary data within this context to communicate with other middleware handling this message.

	ID     string      // Request ID.
	Method string      // Called method.
	Res    interface{} // Response to be returned.
	Err    *ResError   // Error to be returned.
	// contains filtered or unexported fields
}

ReqCtx is the request context.

func (*ReqCtx) Next

func (ctx *ReqCtx) Next() error

Next executes the next middleware in the middleware stack.

func (*ReqCtx) Params

func (ctx *ReqCtx) Params(v interface{}) error

Params reads request parameters into given object. Object should be passed by reference.

type ResCtx

type ResCtx struct {
	Conn *Conn // Client connection.

	ID           string // Message ID.
	Success      bool   // If response is a success or error response.
	ErrorCode    int    // Error code (if any).
	ErrorMessage string // Error message (if any).
	// contains filtered or unexported fields
}

ResCtx is the response context.

func (*ResCtx) ErrorData

func (ctx *ResCtx) ErrorData(v interface{}) error

ErrorData reads the error response data into given object. Object should be passed by reference.

func (*ResCtx) Result

func (ctx *ResCtx) Result(v interface{}) error

Result reads response result data into given object. Object should be passed by reference.

type ResError

type ResError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

ResError is a JSON-RPC response error object representation for outgoing responses.

type Server

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

Server is a Neptulon server.

func NewServer

func NewServer(addr string) *Server

NewServer creates a new Neptulon server. addr should be formatted as host:port (i.e. 127.0.0.1:3000)

func (*Server) Close

func (s *Server) Close() error

Close closes the network listener and the active connections.

func (*Server) DisconnHandler

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

DisconnHandler registers a function to handle client disconnection events.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the Neptulon server. This function blocks until server is closed.

func (*Server) Middleware

func (s *Server) Middleware(middleware ...Middleware)

Middleware registers middleware to handle incoming request messages.

func (*Server) MiddlewareFunc

func (s *Server) MiddlewareFunc(middleware ...func(ctx *ReqCtx) error)

MiddlewareFunc registers middleware function to handle incoming request messages.

func (*Server) SendRequest

func (s *Server) SendRequest(connID string, method string, params interface{}, resHandler func(ctx *ResCtx) error) (reqID string, err error)

SendRequest sends a JSON-RPC request through the connection denoted by the connection ID with an auto generated request ID. resHandler is called when a response is returned.

func (*Server) SendRequestArr

func (s *Server) SendRequestArr(connID string, method string, resHandler func(ctx *ResCtx) error, params ...interface{}) (reqID string, err error)

SendRequestArr sends a JSON-RPC request through the connection denoted by the connection ID, with array params and auto generated request ID. resHandler is called when a response is returned.

func (*Server) UseTLS

func (s *Server) UseTLS(cert, privKey, clientCACert []byte) error

UseTLS enables Transport Layer Security for the connections. cert, key = Server certificate/private key pair. clientCACert = Optional certificate for verifying client certificates. All certificates/private keys are in PEM encoded X.509 format.

func (*Server) Wait

func (s *Server) Wait()

Wait waits for all message/connection handler goroutines in all connections to exit.

Directories

Path Synopsis
jwt

Jump to

Keyboard shortcuts

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