relay

package
v0.0.0-...-e16d50f Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2015 License: MIT Imports: 27 Imported by: 0

README

#Relay GoDoc Travis

Relay is a simple microframework with very simple designs that provide you with the minimal tools you need to get things running.

Download

 go get github.com/influx6/relay/...

Install

 go install github.com/influx6/relay/...

Example

  #file: app.yaml

  addr: ":3000"

  folders:
    assets: ./app/assets
    models: ./app/models
    views: ./app/views


  package app

  import (
  	"log"
  	"os"

  	"github.com/gorilla/websocket"
  	"github.com/influx6/relay/relay"
  	"github.com/influx6/relay/engine"
  )

  conf := engine.NewConfig()

  //can be loaded from a file
	if err := conf.Load("./app.yaml"); err != nil {
		log.Printf("Error occured loading config: %s", err.Error())
		return
	}

	app := engine.NewEngine(conf)

  app.Chain(relay.Logger(nil))

  //using the middleware router
  	app.Rule("get head", "/favicon.ico", nil).Chain(relay.Redirect("/static/images/favicon.ico"))

  //the internal router allows the specification of
  //request methods to handle  for this route as a list of space seperated values
  app.Rule("get head delete","/jails",func(c *relay.Context,next relay.NextHandler){
    //handle the request and response
  })

  //if its an empty string then all methods are allowed
  app.Rule("","/updates",func(c *relay.Context,next relay.NextHandler){
    //handle the request and response
  })

  // Using Codecs
  //if its an empty string then all methods are allowed
  app.Rule("","/updates",func(c *relay.Context,next relay.NextHandler){
    //handle the request and response
  })


  ```

  - Using the relay codecs system:

  ```go

      app.Rule("get post put","/:names",func(c *relay.Context,nx relay.NextHandler){
        //handle the custom request object
          json := JSONRender(200,map[string]string{"user":"john"}, true, true, true)

          //a special header encoder that uses the Context itself for some head writing
          BasicHeadEncoder.Encode(c, json.Head)

          //Encoders take in a io.Writer
          JSONEncoder.Encode(c.Res, json)
        nx(req)
      })

  ```

  - Using websockets:

  ```go

  //use Link() to branch out into a new chain tree
  app.Rule("get post put","/socket").Link(relay.FlatSocket(nil,func(soc *relay.SocketWorker){

    for data := range soc.Messages {

      //the raw message provided by gorilla.webocket
      words := data.Message()

      if err != nil {
        continue
      }

      // if we use the default codec BasicSocketCodec,
      //then a []byte is returned but the codec used is up
      //to you,so this can be any thing your codec returns
      bu := words.([]byte)

      //using the gorilla.Conn wraped by relay.WebSocket directly
      err := data.Socket.WriteMessage(....)
    }


  },nil)) // => returns a FlatChain middleware

  //Strategy two:
  //for a more chat like experience use for websocket, apart
  //from rolling out your own registration and broadcast units,
  //you can use the relay.SocketHub which takes each socket,registers it
  //and automatically receives messages from it and other registed sockets
  //and calls the supplied handler callback as below.
  //SocketHub provides a distribute function can exclude one supplied socket
  //from the message its sending to the others,to allow a reply approach

  //Has below lets create a central socket hub for the message and reply process of
  //the incoming sockets
  sockhub := relay.NewSocketHub(func(hub *relay.SocketHub, msg *relay.WebsocketMessage){
    //handle the message
    data,err := msg.Message()

    //distribute reply to others, but excluding the sender which can be
    //passed as the second argument
    hub.Distribute(func(other *relay.SocketWorker){

      //for more freedom you can write directly skipping the codec encoder
      other.Socket().WriteMessage(...)

    },msg.Worker)

  })

  app.Rule("get post put","/socket",nil).Link(relay.FlatSocket(nil,hub.AddConnection,nil))

	app.Serve()

#License

. MIT

Documentation

Index

Constants

View Source
const (
	// ContentBinary header value for binary data.
	ContentBinary = "application/octet-stream"
	// ContentHTML header value for HTML data.
	ContentHTML = "text/html"
	// ContentJSON header value for JSON data.
	ContentJSON = "application/json"
	// ContentJSONP header value for JSONP data.
	ContentJSONP = "application/javascript"
	// ContentLength header constant.
	ContentLength = "Content-Length"
	// ContentText header value for Text data.
	ContentText = "text/plain"
	// ContentType header constant.
	ContentType = "Content-Type"
	// ContentXHTML header value for XHTML data.
	ContentXHTML = "application/xhtml+xml"
	// ContentXML header value for XML data.
	ContentXML = "text/xml"
)

Variables

View Source
var (
	// ErrTimeout provides a timeout error
	ErrTimeout = errors.New("Timeout on Connection")

	// ErrorNotFind stands for errors when value not find
	ErrorNotFind = errors.New("NotFound!")
	// ErrorBadRequestType stands for errors when the interface{} recieved can not
	// be type asserted as a *http.Request object
	ErrorBadRequestType = errors.New("type is not a *http.Request")
	// ErrorBadHTTPPacketType stands for errors when the interface{} received is not a
	//bad request type
	ErrorBadHTTPPacketType = errors.New("type is not a HTTPPacket")
	// ErrorNoConnection describe when a link connection does not exists"
	ErrorNoConnection = errors.New("NoConnection")
	// ErrBadConn represent a bad connection
	ErrBadConn = errors.New("Bad Connection Received")
)

BasicHTTPCodec returns a new codec based on the basic deocder and encoder

View Source
var BasicHeadEncoder = NewHeadEncoder(func(c *Context, h *Head) error {
	WriteHead(c, h)
	return nil
})

BasicHeadEncoder provides a basic encoder for writing the response headers and status information,it provides the flexibility to build even more reusable and useful header writing methods

BasicSocketCodec returns a codec using the socket encoder and decoder

View Source
var ByteEncoder = NewEncoder(func(w io.Writer, bu interface{}) (int, error) {
	bo, ok := bu.([]byte)

	if !ok {
		return 0, ErrInvalidByteType
	}

	return w.Write(bo)
})

ByteEncoder provides the basic websocket message encoder for encoding json messages

View Source
var ByteSocketDecoder = NewSocketDecoder(func(t int, bu []byte) (interface{}, error) {
	return bu, nil
})

ByteSocketDecoder provides the basic websocket decoder which justs returns a decoder

View Source
var ErrClosed = errors.New("Already Closed")

ErrClosed is returned to indicated an already closed struct

View Source
var ErrInvalidByteType = errors.New("interface not a []byte")

ErrInvalidByteType is returned when the interface is ot a []byte

View Source
var ErrInvalidType = errors.New("Unsupported Type")

ErrInvalidType is returned when the type required is not met

View Source
var ErrNoBody = errors.New("Http Request Has no body")

ErrNoBody is returned when the request has no body

View Source
var ErrNotHTTP = errors.New("interface type is not HTTPRequest")

ErrNotHTTPParameter is returned when an HTTPort receives a wrong interface type

View Source
var ErrNotHijackable = errors.New("ResponseWriter cant be Hijacked")

ErrNotHijackable is returned when a response writer can not be hijacked

View Source
var HTMLEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {

	hop, ok := d.(*HTML)

	if !ok {
		return 0, NewCustomError("HTML", "encoder received wrong type,expected HTML struct type")
	}

	bou := bufPool.Get()

	if err := hop.Template.ExecuteTemplate(bou, hop.Layout, hop.Binding); err != nil {
		return 0, err
	}

	nd, err := bou.WriteTo(w)

	bufPool.Put(bou)

	return int(nd), err
})

HTMLEncoder provides the jsonp encoder for encoding json messages

View Source
var JSONEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {

	jso, ok := d.(*JSON)

	if !ok {
		return 0, NewCustomError("JSON", "Wrong type,expected JSON type")
	}

	if jso.Stream {
		return 1, json.NewEncoder(w).Encode(jso.Data)
	}

	var res []byte
	var err error

	if jso.Indent {
		res, err = json.MarshalIndent(jso.Data, "", "  ")
		res = append(res, '\n')
	} else {
		res, err = json.Marshal(jso.Data)
	}

	if err != nil {
		return 0, err
	}

	if jso.UnEscapeHTML {
		res = bytes.Replace(res, []byte("\\u003c"), []byte("<"), -1)
		res = bytes.Replace(res, []byte("\\u003e"), []byte(">"), -1)
		res = bytes.Replace(res, []byte("\\u0026"), []byte("&"), -1)
	}

	w.Write(res)

	return 0, nil
})

JSONEncoder provides the jsonp encoder for encoding json messages

View Source
var JSONPEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {
	var res []byte
	var err error

	jop, ok := d.(*JSONP)

	if !ok {
		return 0, NewCustomError("JSONP", "encoder expected JSONP type")
	}

	if jop.Indent {
		res, err = json.MarshalIndent(jop.Data, "", "  ")
		res = append(res, '\n')
	} else {
		res, err = json.Marshal(jop.Data)
	}

	if err != nil {
		return 0, err
	}

	var fos []byte
	fos = append(fos, []byte(jop.Callback+"(")...)
	fos = append(fos, res...)
	fos = append(fos, []byte(");")...)

	return w.Write(fos)
})

JSONPEncoder provides the jsonp encoder for encoding json messages

View Source
var MessageDecoder = NewHTTPDecoder(func(req *Context) (*Message, error) {
	return loadData(req)
})

MessageDecoder provides the message decoding decoder for *Context objects

View Source
var SimpleEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {

	switch d.(type) {
	case string:
		so, _ := d.(string)
		return w.Write([]byte(so))
	case []byte:
		bo, _ := d.([]byte)
		return w.Write(bo)
	}

	return 0, NewCustomError("SimpleEncoder", "data is neither a 'string' or '[]byte' type ")
})

SimpleEncoder provides simple encoding that checks if the value given is a string or []byte else returns an error

View Source
var TextEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {
	tx, ok := d.(*Text)

	if !ok {
		return 0, NewCustomError("TextEncoder", "received type is not a Text{}")
	}

	return w.Write([]byte(tx.Data))
})

TextEncoder provides the jsonp encoder for encoding json messages

View Source
var XMLEncoder = NewEncoder(func(w io.Writer, d interface{}) (int, error) {

	jso, ok := d.(*XML)

	if !ok {
		return 0, NewCustomError("XML", "Wrong type,expected XML type")
	}

	var res []byte
	var err error

	if jso.Indent {
		res, err = xml.MarshalIndent(jso.Data, "", "  ")
		res = append(res, '\n')
	} else {
		res, err = xml.Marshal(jso.Data)
	}

	if err != nil {
		return 0, err
	}

	return w.Write(res)
})

XMLEncoder provides the jsonp encoder for encoding json messages

Functions

func CreateHTTP

func CreateHTTP(addr string, handle http.Handler) (*http.Server, net.Listener, error)

CreateHTTP returns a http server using the giving address

func CreateTLS

func CreateTLS(addr string, conf *tls.Config, handle http.Handler) (*http.Server, net.Listener, error)

CreateTLS returns a http server using the giving address

func GetMethods

func GetMethods(m string) []string

GetMethods turns a string of space separated methods into a list

func HasMethod

func HasMethod(mo []string, m string) bool

HasMethod returns true/false if a method is found in a list of method names

func IdentityCall

func IdentityCall(c *Context, nx NextHandler)

IdentityCall provides a Identity caller for FlatHandler

func IsWebSocketRequest

func IsWebSocketRequest(r *http.Request) bool

IsWebSocketRequest returns true if a http.Request object is based on websocket standards

func LoadTLS

func LoadTLS(cert, key string) (*tls.Config, error)

LoadTLS loads a tls.Config from a key and cert file path

func LunchHTTP

func LunchHTTP(addr string, handle http.Handler) error

LunchHTTP returns a http server using the giving address

func LunchTLS

func LunchTLS(addr string, conf *tls.Config, handle http.Handler) error

LunchTLS returns a http server using the giving address

func MakeBaseListener

func MakeBaseListener(addr string, conf *tls.Config) (net.Listener, error)

MakeBaseListener returns a new net.Listener(*TCPKeepAliveListener) for http.Request

func MakeBaseServer

func MakeBaseServer(l net.Listener, handle http.Handler, c *tls.Config) (*http.Server, net.Listener, error)

MakeBaseServer returns a new http.Server using the provided listener

func MakeListener

func MakeListener(addr, ts string, conf *tls.Config) (net.Listener, error)

MakeListener returns a new net.Listener for http.Request

func MatchesMethod

func MatchesMethod(mo []string, w http.ResponseWriter, r *http.Request, c Collector, fx RHandler)

MatchesMethod provides a factory function for matching sets of methods against a reqests method

func ServeFile

func ServeFile(indexFile, dir, file string, res http.ResponseWriter, req *http.Request) error

ServeFile provides a file handler for serving files, it takes an indexFile which defines a default file to look for if the file path is a directory ,then the directory to use and the file to be searched for

func WriteHead

func WriteHead(c *Context, h *Head)

WriteHead uses a context and writes into the resposne with a head struct

func WriteRawHead

func WriteRawHead(c http.ResponseWriter, h *Head)

WriteRawHead writes a head struct into a ResponseWriter

Types

type BufferPool

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

BufferPool implements a pool of bytes.Buffers in the form of a bounded channel. Pulled from the github.com/oxtoacart/bpool package (Apache licensed).

func NewBufferPool

func NewBufferPool(size int, mem int) (bp *BufferPool)

NewBufferPool creates a new BufferPool bounded to the given size.

func (*BufferPool) Get

func (bp *BufferPool) Get() (b *bytes.Buffer)

Get gets a Buffer from the BufferPool, or creates a new one if none are available in the pool.

func (*BufferPool) Put

func (bp *BufferPool) Put(b *bytes.Buffer)

Put returns the given Buffer to the BufferPool.

type ChainRouta

type ChainRouta struct {
	*reggy.ClassicMatchMux
	Handler RHandler
}

ChainRouta provides a single routing rule instance for Router

type ChainRouter

type ChainRouter struct {
	FlatChains

	Fail RHandler
	Log  *log.Logger
	// contains filtered or unexported fields
}

ChainRouter provides an alternative routing strategy of registered ChainRoutas using the FlatChains, its process is when any stack matches, its passed the requests to that handler and continues on, but if non matching is found,it executes a failure routine i.e it matches as many as possible unless non matches

func NewChainRouter

func NewChainRouter(fail RHandler, lg *log.Logger) *ChainRouter

NewChainRouter returns a new ChainRouter instance

func (*ChainRouter) BareRule

func (r *ChainRouter) BareRule(mo, pattern string, fx RHandler)

BareRule defines a matching rule for a specified pattern

func (*ChainRouter) Handle

func (r *ChainRouter) Handle(w http.ResponseWriter, rq *http.Request, _ Collector)

Handle meets the FlatHandler interface for serving http requests

func (*ChainRouter) Rule

func (r *ChainRouter) Rule(mo, pattern string, fx FlatHandler) FlatChains

Rule defines a matching rule which returns a flatchain

func (*ChainRouter) ServeHTTP

func (r *ChainRouter) ServeHTTP(w http.ResponseWriter, rq *http.Request)

ServeHTTP provides the handling of http requests and meets the http.Handler interface

type Collector

type Collector map[string]interface{}

Collector defines a typ of map string

func NewCollector

func NewCollector() Collector

NewCollector returns a new collector instance

func (Collector) Clear

func (c Collector) Clear()

Clear clears the collector

func (Collector) Clone

func (c Collector) Clone() Collector

Clone makes a new clone of this collector

func (Collector) Copy

func (c Collector) Copy(m map[string]interface{})

Copy copies the map into the collector

func (Collector) Each

func (c Collector) Each(fx StringEachfunc)

Each iterates through all items in the collector

func (Collector) Get

func (c Collector) Get(k string) interface{}

Get returns the value with the key

func (Collector) Has

func (c Collector) Has(k string) bool

Has returns if a key exists

func (Collector) HasMatch

func (c Collector) HasMatch(k string, v interface{}) bool

HasMatch checks if key and value exists and are matching

func (Collector) Keys

func (c Collector) Keys() []string

Keys return the keys of the Collector

func (Collector) Remove

func (c Collector) Remove(k string)

Remove deletes a key:value pair

func (Collector) Set

func (c Collector) Set(k string, v interface{})

Set puts a specific key:value into the collector

func (Collector) ToMap

func (c Collector) ToMap() map[string]interface{}

ToMap makes a new clone of this map[string]interface{}

type Context

type Context struct {
	*SyncCollector
	Req *http.Request
	Res ResponseWriter
	Log *log.Logger
}

Context provides a resource holder for each request and response pair with internal mappings for storing data

func NewContext

func NewContext(res http.ResponseWriter, req *http.Request) *Context

NewContext returns a new http context

func NewContextWith

func NewContextWith(res http.ResponseWriter, req *http.Request, loga *log.Logger) *Context

NewContextWith returns a new http context with a custom logger

type CustomError

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

CustomError provides a custom error message format using a message pattern 'title: message'

func NewCustomError

func NewCustomError(title, mesg string) CustomError

NewCustomError provides a function instance generator

func (CustomError) Error

func (c CustomError) Error() string

Error returns the error message

func (CustomError) String

func (c CustomError) String() string

String returns the message of the CustomError struct

type EncodeHandler

type EncodeHandler func(io.Writer, interface{}) (int, error)

EncodeHandler provides a handler for http encoding function

type Encoder

type Encoder interface {
	Encode(io.Writer, interface{}) (int, error)
}

Encoder takes an inteface and encodes it into a []byte slice

func NewEncoder

func NewEncoder(fx EncodeHandler) Encoder

NewEncoder provides a nice way of build an Encoder

type FS

type FS struct {
	http.FileSystem
	Strip  string
	Header http.Header
}

FS provides a configurable struct that provides a http.FileSystem with extra customization options

func NewFS

func NewFS(fs http.FileSystem, strip string) *FS

NewFS returns a custom http.FileSystem with extra extensions in tailoring response

func UseFS

func UseFS(fs http.FileSystem, hd http.Header, strip string) *FS

UseFS returns a custom http.FileSystem with extra extensions in tailoring response

type FlatChain

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

FlatChain provides a simple middleware like

func NewFlatChain

func NewFlatChain(fx FlatHandler, loga *log.Logger) *FlatChain

NewFlatChain returns a new flatchain instance

func (*FlatChain) Chain

func (r *FlatChain) Chain(rx FlatChains) FlatChains

Chain sets the next flat chains else passes it down to the last chain to set as next chain,returning itself

func (*FlatChain) ChainFlat

func (r *FlatChain) ChainFlat(h FlatHandler) FlatChains

ChainFlat returns a new flatchain using a provided FlatHandler

func (*FlatChain) ChainHandleFunc

func (r *FlatChain) ChainHandleFunc(h http.HandlerFunc) FlatChains

ChainHandleFunc returns a new flatchain using a http.HandlerFunc as a chain wrap

func (*FlatChain) ChainHandler

func (r *FlatChain) ChainHandler(h http.Handler) FlatChains

ChainHandler returns a new flatchain using a http.Handler as a chain wrap

func (*FlatChain) Handle

func (r *FlatChain) Handle(res http.ResponseWriter, req *http.Request, co Collector)

Handle calls the next chain if any

func (*FlatChain) HandleContext

func (r *FlatChain) HandleContext(c *Context)

HandleContext calls the next chain if any

func (r *FlatChain) Link(rx FlatChains) FlatChains

Link connects a new FlatChain but bounds it as a new unique chain and not part of the current chain of the FlatChain being connected to

func (*FlatChain) LinkFlat

func (r *FlatChain) LinkFlat(h FlatHandler) FlatChains

LinkFlat returns a new flatchain using a provided FlatHandler

func (*FlatChain) LinkHandleFunc

func (r *FlatChain) LinkHandleFunc(h http.HandlerFunc) FlatChains

LinkHandleFunc returns a new flatchain using a http.HandlerFunc as a chain wrap

func (*FlatChain) NChain

func (r *FlatChain) NChain(rx FlatChains) FlatChains

NChain sets the next flat chains else passes it down to the last chain to set as next chain,returning the the supplied chain

func (*FlatChain) ServeHTTP

func (r *FlatChain) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP calls the next chain if any

type FlatChains

type FlatChains interface {
	ChainHandleFunc(h http.HandlerFunc) FlatChains
	ChainHandler(h http.Handler) FlatChains
	ChainFlat(h FlatHandler) FlatChains
	ServeHTTP(http.ResponseWriter, *http.Request)
	Handle(http.ResponseWriter, *http.Request, Collector)
	HandleContext(*Context)
	Chain(FlatChains) FlatChains
	NChain(FlatChains) FlatChains
}

FlatChains define a simple flat chain

func ChainFlats

func ChainFlats(mo FlatChains, so ...FlatChains) FlatChains

ChainFlats chains second flats to the first flatchain and returns the first flatchain

func ChooseFlat

func ChooseFlat(methods, pattern string, pass, fail FlatChains, lg *log.Logger) FlatChains

ChooseFlat provides a binary operation for handling routing using flatchains,it inspects the requests where if it matches its validation parameters, the `pass` chain is called else calls the 'fail' chain if no match but still passes down the requests through the returned chain

func FlatChainHandlerWrap

func FlatChainHandlerWrap(h http.Handler, lg *log.Logger) FlatChains

FlatChainHandlerWrap provides a chain wrap for http.Handler with an optional log argument

func FlatChainIdentity

func FlatChainIdentity(lg *log.Logger) FlatChains

FlatChainIdentity returns a chain that calls the next automatically

func FlatChainWrap

func FlatChainWrap(h http.HandlerFunc, lg *log.Logger) FlatChains

FlatChainWrap provides a chain wrap for http.Handler with an optional log argument

func FlatHandleFunc

func FlatHandleFunc(methods, pattern string, r http.HandlerFunc, lg *log.Logger) FlatChains

FlatHandleFunc returns a FlatChain that wraps a http.HandleFunc for execution

func FlatHandleHandler

func FlatHandleHandler(methods, pattern string, r http.Handler, lg *log.Logger) FlatChains

FlatHandleHandler returns a flatchain that wraps a http.Handler

func FlatPass

func FlatPass(methods, pattern string, lg *log.Logger) FlatChains

FlatPass uses FlatRoute but passes on the next caller immediately

func FlatRoute

func FlatRoute(methods, pattern string, fx FlatHandler, lg *log.Logger) FlatChains

FlatRoute provides a new routing system based on the middleware stack and if a request matches then its passed down the chain else ignored

func FlatRouteBuild

func FlatRouteBuild(methods []string, pattern *reggy.ClassicMatchMux, fx FlatHandler, lg *log.Logger) FlatChains

FlatRouteBuild lets you control what methods and matcher gets used to create a flatchain

func FlatSocket

func FlatSocket(header http.Header, hs SocketHandler, logg *log.Logger) FlatChains

FlatSocket returns a socket Chain using a default upgraders

func Logger

func Logger(log *log.Logger) FlatChains

Logger returns a new logger chain for logger incoming requests using a custom logger

func NewSockets

func NewSockets(upgrader *websocket.Upgrader, headers http.Header, hs SocketHandler, logg *log.Logger) FlatChains

NewSockets returns a new websocket port

func Redirect

func Redirect(path string) FlatChains

Redirect redirects all incoming request to the path

func ThenFlat

func ThenFlat(methods, pattern string, pass FlatChains, log *log.Logger) FlatChains

ThenFlat provides a binary operation for handling routing using flatchains,it inspects the requests where if it matches the given criteria passes off to the supplied Chain else passes it down its own chain scope

type FlatHandler

type FlatHandler func(*Context, NextHandler)

FlatHandler provides a handler for flatchain

func FSContextHandler

func FSContextHandler(fs *FS, fail http.HandlerFunc) FlatHandler

FSContextHandler returns a valid FlatHandler

func FSCtxHandler

func FSCtxHandler(fs *FS) FlatHandler

FSCtxHandler returns a valid FlatHandler

func FlatHandlerFuncWrap

func FlatHandlerFuncWrap(h http.HandlerFunc) FlatHandler

FlatHandlerFuncWrap provides a chain wrap for http.Handler with an optional log argument

func FlatHandlerWrap

func FlatHandlerWrap(h http.Handler) FlatHandler

FlatHandlerWrap provides a chain wrap for http.Handler with an optional log argument

func LoggerHandler

func LoggerHandler() FlatHandler

LoggerHandler creates a new FlatHandler using a giving log instance

func PanicContextHandler

func PanicContextHandler(fx FlatHandler, p func(*Context, interface{})) FlatHandler

PanicContextHandler returns a new FlatHandler which handles panics which may occure

func PanicFlatHandler

func PanicFlatHandler(fx FlatHandler, p PanicHandler) FlatHandler

PanicFlatHandler returns a new FlatHandler which handles panics which may occure

type HTML

type HTML struct {
	*Head
	Layout   string
	Binding  interface{}
	Template *template.Template
}

HTML provides a basic html messages

func HTMLRender

func HTMLRender(status int, layout string, binding interface{}, tl *template.Template) *HTML

HTMLRender returns a html struct for rendering

type HTTPCodec

type HTTPCodec interface {
	Encoder
	HTTPDecoder
}

HTTPCodec provides a interface define method for custom message formats

func NewHTTPCodec

func NewHTTPCodec(e Encoder, d HTTPDecoder) HTTPCodec

NewHTTPCodec returns a new http codec

func UseHTTPEncoder

func UseHTTPEncoder(enc Encoder) HTTPCodec

UseHTTPEncoder wires up the MessageDecoder as an automatic decoder

type HTTPDecodeHandler

type HTTPDecodeHandler func(*Context) (*Message, error)

HTTPDecodeHandler provides a base decoder function type

type HTTPDecoder

type HTTPDecoder interface {
	Decode(*Context) (*Message, error)
}

HTTPDecoder provides a single member rule that takes a []byte and decodes it into its desired format

func NewHTTPDecoder

func NewHTTPDecoder(fx HTTPDecodeHandler) HTTPDecoder

NewHTTPDecoder provides a nice way of build an HTTPEncoder

type Head struct {
	Status  int
	Content string
	Headers http.Header
}

Head provides a basic message status and head values

type HeadEncodeHandler

type HeadEncodeHandler func(*Context, *Head) error

HeadEncodeHandler provides a handler for http encoding function

type HeadEncoder

type HeadEncoder interface {
	Encode(*Context, *Head) error
}

HeadEncoder takes an inteface and encodes it into a []byte slice

func NewHeadEncoder

func NewHeadEncoder(fx HeadEncodeHandler) HeadEncoder

NewHeadEncoder provides a nice way of build an http headers encoders

type JSON

type JSON struct {
	*Head
	Indent       bool
	UnEscapeHTML bool
	Stream       bool
	Data         interface{}
}

JSON provides a basic json messages

func JSONRender

func JSONRender(status int, data interface{}, indent, stream, unescape bool) *JSON

JSONRender returns a json struct for rendering

type JSONP

type JSONP struct {
	*Head
	Indent   bool
	Callback string
	Data     interface{}
}

JSONP provides a basic jsonp messages

func JSONPRender

func JSONPRender(status int, indent bool, callback string, data interface{}) *JSONP

JSONPRender returns a jsonp struct for rendering

type Message

type Message struct {
	Queries     url.Values
	MessageType string
	Method      string
	Payload     []byte
	Form        url.Values
	PostForm    url.Values
	Multipart   *multipart.Form
	Params      Collector
}

Message represent a message data

type NextHandler

type NextHandler func(*Context)

NextHandler provides next call for flat chains

type PProf

type PProf struct{}

PProf provide pprofile handlers

func NewPProf

func NewPProf(r *ChainRouter) *PProf

NewPProf provides an instantiated endpoint for pprofiles

func (*PProf) Index

func (p *PProf) Index(c *Context, next NextHandler)

Index provides the pprof Index endpoint

func (*PProf) Profile

func (p *PProf) Profile(c *Context, next NextHandler)

Profile provides the pprof Profile endpoint

func (*PProf) Symbol

func (p *PProf) Symbol(c *Context, next NextHandler)

Symbol provides the pprof Symbol endpoint

func (*PProf) Trace

func (p *PProf) Trace(c *Context, next NextHandler)

Trace provides the pprof Trace endpoint

type PanicHandler

type PanicHandler func(http.ResponseWriter, *http.Request, interface{})

PanicHandler provides a panic function type for requests

type RHandler

type RHandler func(http.ResponseWriter, *http.Request, Collector)

RHandler provides a custom route handler for http request with params

func BuildMatchesMethod

func BuildMatchesMethod(mo []string, fx RHandler) RHandler

BuildMatchesMethod returns RHandler which matches the methods of a request to a list of accepted methods to decided wether to run a RHandler function

func FSHandler

func FSHandler(fs *FS, fail http.HandlerFunc) RHandler

FSHandler returns a valid Route.RHandler for use with the relay.Route

func FSServe

func FSServe(fs http.FileSystem, stripPrefix string, fail http.HandlerFunc) RHandler

FSServe provides a http.Handler for serving using a http.FileSystem

func WrapRouteHandler

func WrapRouteHandler(r http.Handler) RHandler

WrapRouteHandler wraps http handler into a router RHandler

func WrapRouteHandlerFunc

func WrapRouteHandlerFunc(r http.HandlerFunc) RHandler

WrapRouteHandlerFunc wraps http handler into a router RHandler

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Hijacker
	// http.CloseNotifier
	Status() int
	Size() int
	Written() bool
	WritePayload(int, []byte) error
}

ResponseWriter provides a clean interface decorated over the http.ResponseWriter

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter) ResponseWriter

NewResponseWriter returns a new responseWriter

type SocketCodec

type SocketCodec interface {
	Encoder
	SocketDecoder
}

SocketCodec provides a interface define method for custom message formats

func NewSocketCodec

func NewSocketCodec(e Encoder, d SocketDecoder) SocketCodec

NewSocketCodec returns a new http codec

type SocketDecodeHandler

type SocketDecodeHandler func(int, []byte) (interface{}, error)

SocketDecodeHandler provides an handler for SocketEncoder

type SocketDecoder

type SocketDecoder interface {
	Decode(int, []byte) (interface{}, error)
}

SocketDecoder decodes a WebsocketMessage

func NewSocketDecoder

func NewSocketDecoder(fx SocketDecodeHandler) SocketDecoder

NewSocketDecoder provides a nice way of build an SocketDecoder

type SocketHandler

type SocketHandler func(*SocketWorker)

SocketHandler provides an handler type without the port option

type SocketHub

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

SocketHub provides a central command for websocket message handling,its the base struct through which different websocket messaging procedures can be implemented on, it provides a go-routine approach,by taking each new websocket connection,stashing it then receiving data from it for processing

func NewSocketHub

func NewSocketHub(fx SocketHubHandler) (sh *SocketHub)

NewSocketHub returns a new SocketHub instance,allows the passing of a codec for encoding and decoding data

func (*SocketHub) AddConnection

func (s *SocketHub) AddConnection(ws *SocketWorker)

AddConnection adds a new socket connection

func (*SocketHub) Close

func (s *SocketHub) Close()

Close closes the hub

func (*SocketHub) CloseNotify

func (s *SocketHub) CloseNotify() <-chan bool

CloseNotify provides a means of checking the close state of the hub

func (*SocketHub) Distribute

func (s *SocketHub) Distribute(hsx SocketWorkerHandler, except *SocketWorker)

Distribute propagates through the set of defined websocket workers and calls a function on it

type SocketHubHandler

type SocketHubHandler func(*SocketHub, *WebsocketMessage)

SocketHubHandler provides a function type that encapsulates the socket hub message operations

type SocketStore

type SocketStore map[*SocketWorker]bool

SocketStore provides a map store for SocketHub

type SocketWorker

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

SocketWorker provides a workpool for socket connections

func NewSocketWorker

func NewSocketWorker(wo *Websocket) *SocketWorker

NewSocketWorker returns a new socketworker instance

func (*SocketWorker) Close

func (s *SocketWorker) Close() error

Close closes the socket read goroutine and notifies a closure using the close channel

func (*SocketWorker) CloseNotify

func (s *SocketWorker) CloseNotify() chan bool

CloseNotify returns a chan that is used to notify closing of socket

func (*SocketWorker) Equals

func (s *SocketWorker) Equals(b interface{}) bool

Equals returns true/false if interface matches

func (*SocketWorker) Messages

func (s *SocketWorker) Messages() <-chan *WebsocketMessage

Messages returns a receive only channel for socket messages

func (*SocketWorker) Socket

func (s *SocketWorker) Socket() *Websocket

Socket returns the internal socket for the worker

type SocketWorkerHandler

type SocketWorkerHandler func(*SocketWorker)

SocketWorkerHandler provides a function type that encapsulates the socket workers

type StringEachfunc

type StringEachfunc func(interface{}, string, func())

StringEachfunc defines the type of the Mappable.Each rule

type SyncCollector

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

SyncCollector provides a mutex controlled map

func NewSyncCollector

func NewSyncCollector() *SyncCollector

NewSyncCollector returns a new collector instance

func (*SyncCollector) Clear

func (c *SyncCollector) Clear()

Clear clears the collector

func (*SyncCollector) Clone

func (c *SyncCollector) Clone() *SyncCollector

Clone makes a new clone of this collector

func (*SyncCollector) Copy

func (c *SyncCollector) Copy(m map[string]interface{})

Copy copies the map into the collector

func (*SyncCollector) Each

func (c *SyncCollector) Each(fx StringEachfunc)

Each iterates through all items in the collector

func (*SyncCollector) Get

func (c *SyncCollector) Get(k string) interface{}

Get returns the value with the key

func (*SyncCollector) Has

func (c *SyncCollector) Has(k string) bool

Has returns if a key exists

func (*SyncCollector) HasMatch

func (c *SyncCollector) HasMatch(k string, v interface{}) bool

HasMatch checks if key and value exists and are matching

func (*SyncCollector) Keys

func (c *SyncCollector) Keys() []string

Keys return the keys of the Collector

func (*SyncCollector) Remove

func (c *SyncCollector) Remove(k string)

Remove deletes a key:value pair

func (*SyncCollector) Set

func (c *SyncCollector) Set(k string, v interface{})

Set puts a specific key:value into the collector

func (*SyncCollector) ToMap

func (c *SyncCollector) ToMap() map[string]interface{}

ToMap makes a new clone of this map[string]interface{}

type TCPKeepAliveListener

type TCPKeepAliveListener struct {
	*net.TCPListener
}

TCPKeepAliveListener provides the same internal wrapping as http keep alive functionalities

func KeepAliveListener

func KeepAliveListener(t *net.TCPListener) *TCPKeepAliveListener

KeepAliveListener returns a new TCPKeepAliveListener

func (*TCPKeepAliveListener) Accept

func (t *TCPKeepAliveListener) Accept() (net.Conn, error)

Accept sets the keep alive features of the tcp listener

type Text

type Text struct {
	*Head
	Data string
}

Text provides a basic text messages

func TextRender

func TextRender(status int, data string) *Text

TextRender returns a text struct for rendering

type Websocket

type Websocket struct {
	*websocket.Conn
	Ctx *Context
}

Websocket provides a cover for websocket connection

type WebsocketMessage

type WebsocketMessage struct {
	*Websocket

	Worker *SocketWorker
	// contains filtered or unexported fields
}

WebsocketMessage provides small abstraction for processing a message

func (*WebsocketMessage) Message

func (m *WebsocketMessage) Message() []byte

Message returns the data of the socket

func (*WebsocketMessage) MessageType

func (m *WebsocketMessage) MessageType() int

MessageType returns the type of the message

type XML

type XML struct {
	*Head
	Indent bool
	Prefix []byte
	Data   interface{}
}

XML provides a basic html messages

func XMLRender

func XMLRender(status int, indent bool, data interface{}, prefix []byte) *XML

XMLRender returns a html struct for rendering

Jump to

Keyboard shortcuts

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