celerity

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

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

Go to latest
Published: Sep 12, 2018 License: MIT Imports: 24 Imported by: 0

README

Coverage Status GoDoc Go Report Card Build Status

celerity

An API Web framework for Go

For more information see http://celerity.5sigma.io

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// GET verb for HTTP requests
	GET = "GET"
	// POST verb for HTTP request
	POST = "POST"
	// PUT verb for HTTP request
	PUT = "PUT"
	// PATCH verb for HTTP requests
	PATCH = "PATCH"
	// DELETE verb for HTTP request
	DELETE = "POST"
	// OPTIONS verb for HTTP request
	OPTIONS = "OPTIONS"
	// ANY can be used to match any method
	ANY = "*"
	//DEV is the development value for the environment flag
	DEV = "dev"
	//PROD is the production value for the environment flag
	PROD = "prod"
	// FS Filesystem interface
	FS = afero.NewOsFs()
)
View Source
var (
	// ChannelEvents are the type of event that occured.
	ChannelEvents = struct {
		Connect    ChannelEventType
		Disconnect ChannelEventType
		Message    ChannelEventType
	}{
		Connect:    "connect",
		Disconnect: "disconnect",
		Message:    "message",
	}
)

Functions

func HandleCLI

func HandleCLI(onRun func() *Server) error

HandleCLI - Use the built in CLI handling for the server.

func RegisterJob

func RegisterJob(job Job)

RegisterJob registers a new job for the job pool. Jobs must be registered before they can be added to the queue.

func RunAt

func RunAt(job Job, t time.Time)

RunAt will run the job at a specifc time. The job will be executed when a worker is available after the time has past.

func RunLater

func RunLater(job Job, d time.Duration)

RunLater schedules a job to execute after a specified amount of time. The job will be executed when a worker is available and the duration has ellapsed.

func RunNow

func RunNow(job Job)

RunNow will queue a job to run immediately. It will be added to the queue and scheduled to run when the next worker is available.

func SetEnvironment

func SetEnvironment(env string)

SetEnvironment sets the currently operating environment.

Types

type BasicRoute

type BasicRoute struct {
	Path    RoutePath
	Method  string
	Handler RouteHandler
}

BasicRoute - A basic route in the server.

func (*BasicRoute) Handle

func (r *BasicRoute) Handle(c Context) Response

Handle processes the request by passing it to the RouteHandler function

func (*BasicRoute) Match

func (r *BasicRoute) Match(method, path string) (bool, string)

Match - Matches the routes path against the incomming url

func (*BasicRoute) RoutePath

func (r *BasicRoute) RoutePath() RoutePath

RoutePath returns the RoutePath for the route.

func (*BasicRoute) String

func (r *BasicRoute) String() string

type Channel

type Channel struct {
	Name    string
	Clients map[*SocketClient]bool

	Handler ChannelHandler

	Rooms map[string]*ChannelRoom
	// contains filtered or unexported fields
}

Channel segments communication into a single context

func NewChannel

func NewChannel(h ChannelHandler) *Channel

NewChannel Undescribed

func (*Channel) Broadcast

func (ch *Channel) Broadcast(msg interface{})

Broadcast send an event to all clients in the channel

func (*Channel) BroadcastRaw

func (ch *Channel) BroadcastRaw(msg []byte)

BroadcastRaw send an event to all clients in the channel

func (*Channel) Open

func (ch *Channel) Open()

Open run the channel and begin processing messages

func (*Channel) Room

func (ch *Channel) Room(name string) *ChannelRoom

Room will return a room for the given name or it will initialize a new room for that name

type ChannelEvent

type ChannelEvent struct {
	Event ChannelEventType
	Data  []byte
}

ChannelEvent is an event that can occure on the socket

func (*ChannelEvent) Extract

func (ce *ChannelEvent) Extract(obj interface{}) error

Extract unmarshals the JSON into a struct

func (*ChannelEvent) ExtractAt

func (ce *ChannelEvent) ExtractAt(path string, obj interface{}) error

ExtractAt Unmarshals JSON at a path into a struct.

func (*ChannelEvent) Get

func (ce *ChannelEvent) Get(path string) gjson.Result

Get returns a value at a JSON path in the data.

type ChannelEventType

type ChannelEventType string

ChannelEventType is an event type for websocket connections. Such as joining, leaving, message arrival, etc.

type ChannelHandler

type ChannelHandler func(*SocketClient, ChannelEvent)

ChannelHandler is the handling function for incomming messages into the channel

type ChannelRoom

type ChannelRoom struct {
	Name    string
	Clients []*SocketClient
	// contains filtered or unexported fields
}

ChannelRoom is a group of socket clients and can be used to partition the clients into arbitrary groups to make it easy to send messages back and fourth.

func NewChannelRoom

func NewChannelRoom(name string, clients ...*SocketClient) *ChannelRoom

NewChannelRoom Undescribed

func (*ChannelRoom) Add

func (r *ChannelRoom) Add(c *SocketClient)

Add adds a client to the room

func (*ChannelRoom) Broadcast

func (r *ChannelRoom) Broadcast(msg interface{})

Broadcast send an event to all clients in the channel

func (*ChannelRoom) BroadcastRaw

func (r *ChannelRoom) BroadcastRaw(msg []byte)

BroadcastRaw send an event to all clients in the channel

func (*ChannelRoom) Remove

func (r *ChannelRoom) Remove(c *SocketClient)

Remove adds a client to the room

type ChannelRoute

type ChannelRoute struct {
	Path    RoutePath
	Channel *Channel
}

ChannelRoute is a server route that serves a websocket connection

func (*ChannelRoute) Handle

func (r *ChannelRoute) Handle(c Context) Response

Handle performs no logic for a websocket connection

func (*ChannelRoute) Match

func (r *ChannelRoute) Match(method string, path string) (bool, string)

Match checks the incoming URI path against the route

func (*ChannelRoute) RoutePath

func (r *ChannelRoute) RoutePath() RoutePath

RoutePath returns the channels route path

type Context

type Context struct {
	Method      string
	Request     *http.Request
	RequestID   string
	URLParams   Params
	QueryParams Params

	Log        *vox.Vox
	Response   Response
	Env        string
	ScopedPath string

	Writer http.ResponseWriter
	Server *Server
	// contains filtered or unexported fields
}

Context A request context object

func NewContext

func NewContext() Context

NewContext Create a new context object

func RequestContext

func RequestContext(r *http.Request) Context

RequestContext - Creates a new context and sets its request.

func (*Context) Body

func (c *Context) Body() []byte

Body returns the request body

func (*Context) E

func (c *Context) E(status int, err error) Response

E is an alias for the Error function.

func (*Context) Error

func (c *Context) Error(status int, err error) Response

Error - Returns a erorr and outputs the passed error message.

func (*Context) Extract

func (c *Context) Extract(obj interface{}) error

Extract - Unmarshal request data into a structure.

func (*Context) ExtractValue

func (c *Context) ExtractValue(path string) gjson.Result

ExtractValue extracts a value from the request body at a specific JSON node.

func (*Context) F

func (c *Context) F(err error) Response

F is an alias for the Fail function

func (*Context) Fail

func (c *Context) Fail(err error) Response

Fail is used for unrecoverable and internal errors. In a production environment the error is not passed to the client. message.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get Return an arbitrary value from the context that was set with the Set function.

func (*Context) Header

func (c *Context) Header(key string) string

Header Request headers

func (*Context) R

func (c *Context) R(obj interface{}) Response

R Alias for Respond

func (*Context) Raw

func (c *Context) Raw(b []byte) Response

Raw returns a response configured to output a raw []byte resposne. This resposne will also skip the response transformation adapter.

func (*Context) Respond

func (c *Context) Respond(obj interface{}) Response

Respond Respond with an object

func (*Context) S

func (c *Context) S(code int) Response

S aliases Status

func (*Context) Set

func (c *Context) Set(key string, v interface{})

Set Set an arbitrary value in the context

func (*Context) SetParams

func (c *Context) SetParams(params map[string]string)

SetParams - Sets the url parameters for the request.

func (*Context) SetQueryParamsFromURL

func (c *Context) SetQueryParamsFromURL(u *url.URL)

SetQueryParamsFromURL - Sets the query parameters for the request.

func (*Context) Status

func (c *Context) Status(code int) Response

Status returns a response with the set status

type FileSystemAdapter

type FileSystemAdapter interface {
	RootPath(string) afero.Fs
}

FileSystemAdapter is the adapter used for gaining access to the file system

var FSAdapter FileSystemAdapter = &OSAdapter{}

FSAdapter is the current method of accessing the file system.

type JSONResponse

type JSONResponse struct {
	RequestID string                 `json:"requestId"`
	Success   bool                   `json:"success"`
	Error     string                 `json:"error"`
	Data      interface{}            `json:"data"`
	Meta      map[string]interface{} `json:"meta"`
}

JSONResponse - used by the JSONResponseAdapter to build the structure of the default JSON response.

type JSONResponseAdapter

type JSONResponseAdapter struct{}

JSONResponseAdapter - Processes an endpoint response into JSON

func (*JSONResponseAdapter) Process

func (ra *JSONResponseAdapter) Process(c Context, r Response) ([]byte, error)

Process - Process the response into JSON data.

type Job

type Job interface {
	Run() error
}

Job is an interface that can be implemented to run work asyncronously using the celerity job pool.

Impementing a job

To create a Job that can be executed via the Job pool it must impement the Run function.

Run() error

The Job itself must be registered with the Job pool prior to being used.

celerity.RegisterJob(&MyJob{})

A simple example

The following is a simplified example of a running a Job.

type MyJob struct {}

func (j MyJob) Run() error {
	return nil
}

celerity.RegisterJob(&MyJob{})

job := MyJob{}

celerity.Run(MyJob)

As a general pattern it is a good idea to put all your Jobs in a separate package and register each one when you bootstrap the celerity server.

type JobTransport

type JobTransport interface {
	Run(job jobInstance)
}

JobTransport is used to connect to the JobManager by default it is setup to connect to a internal job manager.

type LocalFileRoute

type LocalFileRoute struct {
	Path      RoutePath
	LocalPath string
}

LocalFileRoute will handle serving a single file from the local file system to a given path.

func (*LocalFileRoute) Handle

func (l *LocalFileRoute) Handle(c Context) Response

Handle sets the response to return a local file.

func (*LocalFileRoute) Match

func (l *LocalFileRoute) Match(method string, path string) (bool, string)

Match checks if the incoming path matches the route path and if the local file exists.

func (*LocalFileRoute) RoutePath

func (l *LocalFileRoute) RoutePath() RoutePath

RoutePath returns the route path for the route.

type LocalPathRoute

type LocalPathRoute struct {
	Path      RoutePath
	LocalPath string
}

LocalPathRoute handles serving any file under a path. If the requested file exists it will be served if not the router will continue processing routes.

func (*LocalPathRoute) Handle

func (l *LocalPathRoute) Handle(c Context) Response

Handle sets the resposne up to serve the local file.

func (*LocalPathRoute) Match

func (l *LocalPathRoute) Match(method string, path string) (bool, string)

Match checks if a file exists under the local path

func (*LocalPathRoute) RoutePath

func (l *LocalPathRoute) RoutePath() RoutePath

RoutePath returns the routepath for the route

type MEMAdapter

type MEMAdapter struct {
	MEMFS afero.Fs
}

MEMAdapter give access to an in memory file system for testing

func NewMEMAdapter

func NewMEMAdapter() *MEMAdapter

NewMEMAdapter creates a new in memory FS adapter for testing

func (*MEMAdapter) RootPath

func (m *MEMAdapter) RootPath(path string) afero.Fs

RootPath reutrns a filesystem with in memory access

type MiddlewareHandler

type MiddlewareHandler func(RouteHandler) RouteHandler

MiddlewareHandler is a function that can be used in scopes and routes to transform the context before the route is processed.

type OSAdapter

type OSAdapter struct{}

OSAdapter gives access to the file system

func (*OSAdapter) RootPath

func (o *OSAdapter) RootPath(path string) afero.Fs

RootPath reutrns a filesystem with OS access

type Params

type Params map[string]string

Params - Stores key value params for URL parameters and query parameters. It offers several helper methods for getting results for a key.

func (Params) Int

func (p Params) Int(key string) int

Int - Returns the int value for a parameter key or ""

func (Params) String

func (p Params) String(key string) string

String - Returns the string value for a parameter key or ""

type Response

type Response struct {
	StatusCode int
	Data       interface{}
	Error      error
	Meta       map[string]interface{}
	Header     http.Header

	Handled bool
	// contains filtered or unexported fields
}

Response - The response object reurned by an endpoint.

func NewErrorResponse

func NewErrorResponse(status int, message string) Response

NewErrorResponse - Return a new error response

func NewResponse

func NewResponse() Response

NewResponse - Create a new response object

func (*Response) IsRaw

func (r *Response) IsRaw() bool

IsRaw determens if the response is a raw response

func (Response) MetaValue

func (r Response) MetaValue(k string, v interface{}) Response

MetaValue sets the metadata key for the response

func (Response) R

func (r Response) R(data interface{}) Response

R aliases Respond

func (*Response) Raw

func (r *Response) Raw() []byte

Raw returns the raw data for the request

func (Response) Respond

func (r Response) Respond(data interface{}) Response

Respond sets teh response data

func (Response) S

func (r Response) S(code int) Response

S aliases Status

func (*Response) SetRaw

func (r *Response) SetRaw(b []byte)

SetRaw sets the responses raw output

func (Response) Status

func (r Response) Status(code int) Response

Status sets the status code for the response

func (*Response) StatusText

func (r *Response) StatusText() string

StatusText returns the text version of the StatusCode

func (*Response) Success

func (r *Response) Success() bool

Success returns true if the response was marked succcessful and if an error is not present

type ResponseAdapter

type ResponseAdapter interface {
	Process(Context, Response) ([]byte, error)
}

ResponseAdapter - Response adapters are used to marshal an endpoint response into bytes

type Route

type Route interface {
	Match(method, path string) (bool, string)
	Handle(Context) Response
	RoutePath() RoutePath
}

Route is an interface that can be implemented by any objects wishing to process url calls.

type RouteHandler

type RouteHandler func(Context) Response

RouteHandler - The handler function that gets called when a route is invoked.

type RoutePath

type RoutePath string

RoutePath - A path for a route or a group.

func (RoutePath) GetURLParams

func (rp RoutePath) GetURLParams(path string) map[string]string

GetURLParams - Returns a map of url param/values based on the path given.

func (RoutePath) Match

func (rp RoutePath) Match(path string) (bool, string)

Match - Matches the routepath aganst an incomming path

type Router

type Router struct {
	Root *Scope
}

Router - The server router stores all routes, groups, and determines what to call when a given path is invoked.

func NewRouter

func NewRouter() *Router

NewRouter - Initailize a new router

func (*Router) Handle

func (r *Router) Handle(c Context, req *http.Request) Response

Handle - Process the inccomming URL and execute the first matching route

type Scope

type Scope struct {
	Path          RoutePath
	Scopes        []*Scope
	Routes        []Route
	Middleware    []MiddlewareHandler
	PreMiddleware []MiddlewareHandler
	// contains filtered or unexported fields
}

Scope - A group of routes and subgroups used to represent the routing structure for the serve.r

func (*Scope) Channel

func (s *Scope) Channel(name, path string, h ChannelHandler)

Channel creates a new channel route

func (*Scope) DELETE

func (s *Scope) DELETE(path string, handler RouteHandler) Route

DELETE creates a route for a DELETE method.

func (*Scope) GET

func (s *Scope) GET(path string, handler RouteHandler) Route

GET creates a route for a GET method.

func (*Scope) Handle

func (s *Scope) Handle(c Context) (res Response)

Handle - Handle an incomming URL

func (*Scope) Match

func (s *Scope) Match(req *http.Request, path string) bool

Match - Check if the scope can handle the incomming url

func (*Scope) PATCH

func (s *Scope) PATCH(path string, handler RouteHandler) Route

PATCH creates a route for a PATCH method.

func (*Scope) POST

func (s *Scope) POST(path string, handler RouteHandler) Route

POST creates a route for a POST method.

func (*Scope) PUT

func (s *Scope) PUT(path string, handler RouteHandler) Route

PUT creates a route for a PUT method.

func (*Scope) Pre

func (s *Scope) Pre(mf ...MiddlewareHandler)

Pre - Registers middleware to be executed when the scope is first matched. This happens before the router searches for routes.

func (*Scope) Route

func (s *Scope) Route(method, path string, handler RouteHandler) Route

Route - Create a new route within the scope

func (*Scope) Scope

func (s *Scope) Scope(path string) *Scope

Scope - Creates a new sub scope

func (*Scope) ServeFile

func (s *Scope) ServeFile(path, localpath string)

ServeFile serves static files at a filepath

func (*Scope) ServePath

func (s *Scope) ServePath(path, staticpath string)

ServePath serves static files at a filepath

func (*Scope) Use

func (s *Scope) Use(mf ...MiddlewareHandler)

Use - Use a middleware function

type Server

type Server struct {
	Router          *Router
	ResponseAdapter ResponseAdapter
	Log             *vox.Vox
	Channels        map[string]*Channel
}

Server - Main server instance

func New

func New() *Server

New - Initialize a new server

func NewServer

func NewServer() *Server

NewServer - Initialize a new server

func (*Server) Channel

func (s *Server) Channel(name, path string, h ChannelHandler)

Channel creates a socket channel at the given path

func (*Server) DELETE

func (s *Server) DELETE(path string, handler RouteHandler) Route

DELETE creates a route for a DELETE method.

func (*Server) GET

func (s *Server) GET(path string, handler RouteHandler) Route

GET creates a route for a GET method.

func (*Server) PATCH

func (s *Server) PATCH(path string, handler RouteHandler) Route

PATCH creates a route for a PATCH method.

func (*Server) POST

func (s *Server) POST(path string, handler RouteHandler) Route

POST creates a route for a POST method.

func (*Server) PUT

func (s *Server) PUT(path string, handler RouteHandler) Route

PUT creates a route for a PUT method.

func (*Server) Pre

func (s *Server) Pre(mw MiddlewareHandler)

Pre - Register prehandle middleware for the root scope.

func (*Server) Route

func (s *Server) Route(method, path string, h RouteHandler)

Route - Set a route on the root scope.

func (*Server) Scope

func (s *Server) Scope(path string) *Scope

Scope creates a new scope from the root scope

func (*Server) ServeFile

func (s *Server) ServeFile(path, rootpath string)

ServeFile serves a static file at a given path

func (*Server) ServeHTTP

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

ServeHTTP - Serves the HTTP request. Complies with http.Handler interface

func (*Server) ServePath

func (s *Server) ServePath(path, rootpath string)

ServePath serves a path of static files rooted at the path given

func (*Server) Start

func (s *Server) Start(host string) error

Start the server.

func (*Server) Use

func (s *Server) Use(mw MiddlewareHandler)

Use - Use a middleware in the root scope.

type SocketClient

type SocketClient struct {
	Context Context
	ID      uint64

	Rooms []*ChannelRoom
	// contains filtered or unexported fields
}

SocketClient wraps an actual websocket connection. It provides the request context as well as helper functions for sending data.

func NewSocketClient

func NewSocketClient(c Context, ch *Channel, conn *websocket.Conn) *SocketClient

NewSocketClient creates a new client to control websocket connections

func (*SocketClient) Channel

func (c *SocketClient) Channel() *Channel

Channel returns the channel the socket belogns to

func (*SocketClient) Send

func (c *SocketClient) Send(msg interface{})

Send sends data to the client

func (*SocketClient) SendRaw

func (c *SocketClient) SendRaw(msg []byte)

SendRaw sends bytes to the client

func (*SocketClient) SendString

func (c *SocketClient) SendString(msg string)

SendString sends a string to the client

type SocketMessage

type SocketMessage struct {
	Client  *SocketClient
	Message []byte
}

SocketMessage can be used by channels to pass around a client client reference and a message

Directories

Path Synopsis
Package celeritytest provides helpers for testing Celerity based applications.
Package celeritytest provides helpers for testing Celerity based applications.

Jump to

Keyboard shortcuts

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