falcore

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2015 License: MIT Imports: 24 Imported by: 21

README

Falcore

Falcore is a framework for constructing high performance, modular HTTP servers in Golang.

Read more on the Falcore project page
Read the package documentation

Documentation

Overview

Falcore is a framework for constructing high performance, modular HTTP servers. For more information, see the project page at http://fitstar.github.io/falcore. Or read the full package documentation at http://godoc.org/github.com/fitstar/falcore.

Index

Constants

View Source
const (
	FINEST level = iota
	FINE
	DEBUG
	TRACE
	INFO
	WARNING
	ERROR
	CRITICAL
)

Log levels, in order of priority

Variables

This section is empty.

Functions

func ByteResponse

func ByteResponse(req *http.Request, status int, headers http.Header, body []byte) *http.Response

Generate an http.Response using a []byte for the body.

func Critical

func Critical(arg0 interface{}, args ...interface{}) error

Log using the packages default logger. You can change the underlying logger using SetLogger

func Debug

func Debug(arg0 interface{}, args ...interface{})

Log using the packages default logger. You can change the underlying logger using SetLogger

func Error

func Error(arg0 interface{}, args ...interface{}) error

Log using the packages default logger. You can change the underlying logger using SetLogger

func Fine

func Fine(arg0 interface{}, args ...interface{})

Log using the packages default logger. You can change the underlying logger using SetLogger

func Finest

func Finest(arg0 interface{}, args ...interface{})

Log using the packages default logger. You can change the underlying logger using SetLogger

func Info

func Info(arg0 interface{}, args ...interface{})

Log using the packages default logger. You can change the underlying logger using SetLogger

func PipeResponse

func PipeResponse(req *http.Request, status int, headers http.Header) (io.WriteCloser, *http.Response)

Generate an http.Response using the read half of an io.Pipe as the Body. Returns the write half of an io.Pipe and the response.

Use this to stream a generated body without buffering first. Don't forget to close the writer when finished. Writes are blocking until something Reads so you must use a separate goroutine for writing. Response will be Transfer-Encoding: chunked.

func SetLogger

func SetLogger(newLogger Logger)

Set the packages static logger. This logger is used by falcore can its subpackages. It is also available through the standalone functions that match the logger interface. The default is a StdLibLogger

func SimpleResponse

func SimpleResponse(req *http.Request, status int, headers http.Header, contentLength int64, body io.Reader) *http.Response

Generate an http.Response using the basic fields Use -1 for the contentLength if you don't know the content length in advance.

func StringResponse

func StringResponse(req *http.Request, status int, headers http.Header, body string) *http.Response

Generate an http.Response using a string for the body.

func TimeDiff

func TimeDiff(startTime time.Time, endTime time.Time) float32

Helper for calculating times. return value in Seconds DEPRECATED: Use endTime.Sub(startTime).Seconds()

func Trace

func Trace(arg0 interface{}, args ...interface{})

Log using the packages default logger. You can change the underlying logger using SetLogger

func Warn

func Warn(arg0 interface{}, args ...interface{}) error

Log using the packages default logger. You can change the underlying logger using SetLogger

Types

type Logger

type Logger interface {
	// Matches the log4go interface
	Finest(arg0 interface{}, args ...interface{})
	Fine(arg0 interface{}, args ...interface{})
	Debug(arg0 interface{}, args ...interface{})
	Trace(arg0 interface{}, args ...interface{})
	Info(arg0 interface{}, args ...interface{})
	Warn(arg0 interface{}, args ...interface{}) error
	Error(arg0 interface{}, args ...interface{}) error
	Critical(arg0 interface{}, args ...interface{}) error
}

Interface for logging from within falcore. You can use your own logger as long as it follows this interface by calling SetLogger.

func NewStdLibLogger

func NewStdLibLogger() Logger

type Pipeline

type Pipeline struct {
	Upstream   *list.List
	Downstream *list.List
}

Pipelines have an Upstream and Downstream list of filters. FilterRequest is called with the Request for all the items in the Upstream list in order UNTIL a Response is returned. Once a Response is returned iteration through the Upstream list is ended, and FilterResponse is called for ALL ResponseFilters in the Downstream list, in order.

If no Response is returned from any of the Upstream filters, then execution of the Downstream is skipped and the server will return a default 404 response.

The Upstream list may also contain instances of Router.

func NewPipeline

func NewPipeline() (l *Pipeline)

func (*Pipeline) FilterRequest

func (p *Pipeline) FilterRequest(req *Request) *http.Response

Pipelines are valid RequestFilters. This makes them nestable.

type PipelineStageStat

type PipelineStageStat struct {
	Name      string
	Type      PipelineStageType
	Status    byte
	StartTime time.Time
	EndTime   time.Time
}

Container for keeping stats per pipeline stage Name for filter stages is reflect.TypeOf(filter).String()[1:] and the Status is 0 unless it is changed explicitly in the Filter or Router.

For the Status, the falcore library will not apply any specific meaning to the status codes but the following are suggested conventional usages that we have found useful

  type PipelineStatus byte
  const (
	    Success PipelineStatus = iota   // General Run successfully
	    Skip                            // Skipped (all or most of the work of this stage)
	    Fail                            // General Fail
	    // All others may be used as custom status codes
  )

func NewPiplineStage

func NewPiplineStage(name string) *PipelineStageStat

type PipelineStageType

type PipelineStageType string

The type of pipeline stage for a stat object. These are included in the (*Request)Trace output.

const (
	PipelineStageTypeOther      PipelineStageType = "OT"
	PipelineStageTypeUpstream   PipelineStageType = "UP"
	PipelineStageTypeDownstream PipelineStageType = "DN"
	PipelineStageTypeRouter     PipelineStageType = "RT"
	PipelineStageTypeOverhead   PipelineStageType = "OH"
)

type Request

type Request struct {
	ID                 string
	StartTime          time.Time
	EndTime            time.Time
	Overhead           time.Duration
	PipelineStageStats *list.List
	CurrentStage       *PipelineStageStat

	RemoteAddr  *net.TCPAddr
	HttpRequest *http.Request
	Context     map[string]interface{}
	// contains filtered or unexported fields
}

Request wrapper

The request is wrapped so that useful information can be kept with the request as it moves through the pipeline.

A pointer is kept to the originating Connection.

Context is provided to allow for passing data between stages. For example, you may have an authentication filter that sets the auth information in Context for use at a later stage.

There is a unique ID assigned to each request. This ID is not globally unique to keep it shorter for logging purposes. It is possible to have duplicates though very unlikely over the period of a day or so. It is a good idea to log the ID in any custom log statements so that individual requests can easily be grepped from busy log files.

Falcore collects performance statistics on every stage of the pipeline. The stats for the request are kept in PipelineStageStats. This structure will only be complete in the Request passed to the pipeline RequestDoneCallback. Overhead will only be available in the RequestDoneCallback and it's the difference between the total request time and the sums of the stage times. It will include things like pipeline iteration and the stat collection itself.

See falcore.PipelineStageStat docs for more info.

func TestWithRequest

func TestWithRequest(request *http.Request, filter RequestFilter, context map[string]interface{}) (*Request, *http.Response)

Returns a completed falcore.Request and response after running the single filter stage The PipelineStageStats is completed in the returned Request The falcore.Request.Connection and falcore.Request.RemoteAddr are nil

func (*Request) Signature

func (fReq *Request) Signature() string

This gives a unique signature for each unique path through the pipeline. The Signature will only be complete in the RequestDoneCallback. At any given time, the Signature is a crc32 sum of all the finished pipeline stages combining PipelineStageStat.Name and PipelineStageStat.Status. To modify the signature for your own use, just set the request.CurrentStage.Status in your RequestFilter or ResponseFilter.

func (*Request) Trace

func (fReq *Request) Trace(res *http.Response)

Call from RequestDoneCallback. Logs a bunch of information about the request to the falcore logger. This is a pretty big hit to performance so it should only be used for debugging or development. The source is a good example of how to get useful information out of the Request.

type RequestCompletionCallback

type RequestCompletionCallback func(req *Request, res *http.Response)

An optional callback called after each request is fully processed and delivered to the client. At this point, it's too late to alter the response. For that, use a ResponseFilter. This is a great place to do things like logging/reporting.

type RequestFilter

type RequestFilter interface {
	FilterRequest(req *Request) *http.Response
}

Filter incomming requests and return a response or nil. Filters are chained together into a flow (the Pipeline) which will terminate if the Filter returns a response.

func NewRequestFilter

func NewRequestFilter(f func(req *Request) *http.Response) RequestFilter

Helper to create a Filter by just passing in a func

   filter = NewRequestFilter(func(req *Request) *http.Response {
			req.Headers.Add("X-Falcore", "is_cool")
			return
		})

type ResponseFilter

type ResponseFilter interface {
	FilterResponse(req *Request, res *http.Response)
}

Filter outgoing responses. This can be used to modify the response before it is sent. Modifying the request at this point will have no effect.

func NewResponseFilter

func NewResponseFilter(f func(req *Request, res *http.Response)) ResponseFilter

Helper to create a Filter by just passing in a func

   filter = NewResponseFilter(func(req *Request, res *http.Response) {
			// some crazy response magic
			return
		})

type Router

type Router interface {
	// Returns a Filter to be executed or nil if one can't be found.
	SelectPipeline(req *Request) (pipe RequestFilter)
}

Interface for defining Routers. Routers may be added to the Pipeline.Upstream, This interface may be used to choose between many mutually exclusive Filters. The Router's SelectPipeline method will be called and if it returns a Filter, the Filter's FilterRequest method will be called. If SelectPipeline returns nil, the next stage in the Pipeline will be executed.

In addition, a Pipeline is itself a RequestFilter so SelectPipeline may return a Pipeline as well. This allows branching of the Pipeline flow.

func NewRouter

func NewRouter(f func(req *Request) (pipe RequestFilter)) Router

Generate a new Router instance using f for SelectPipeline

type Server

type Server struct {
	Addr               string
	Pipeline           *Pipeline
	CompletionCallback RequestCompletionCallback

	AcceptReady <-chan struct{}

	PanicHandler func(conn net.Conn, err interface{})
	// contains filtered or unexported fields
}

A falcore server. This is the thing that actually does the socket stuff and processes requests.

func NewServer

func NewServer(port int, pipeline *Pipeline) *Server

func (*Server) FdListen

func (srv *Server) FdListen(fd int) error

Setup the server to listen using an existing file pointer. If this is set, server will not open a new listening socket.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

Start the server. This method blocks until the server has stopped completely.

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

Start the server using TLS for serving HTTPS.

func (*Server) Port

func (srv *Server) Port() int

The port the server is listening on

func (*Server) ServeHTTP

func (srv *Server) ServeHTTP(wr http.ResponseWriter, req *http.Request)

For compatibility with net/http.Server or Google App Engine If you are using falcore.Server as a net/http.Handler, you should not call any of the Listen methods

func (*Server) SocketFd

func (srv *Server) SocketFd() int

Get the file descriptor from the listening socket.

func (*Server) StopAccepting

func (srv *Server) StopAccepting()

Gracefully shutdown the server. Calling this more than once will result in a panic.

type StdLibLogger

type StdLibLogger struct{}

This is a simple Logger implementation that uses the go log package for output. It's not really meant for production use since it isn't very configurable. It is a sane default alternative that allows us to not have any external dependencies. Use timber or log4go as a real alternative.

func (StdLibLogger) Critical

func (fl StdLibLogger) Critical(arg0 interface{}, args ...interface{}) error

func (StdLibLogger) Debug

func (fl StdLibLogger) Debug(arg0 interface{}, args ...interface{})

func (StdLibLogger) Error

func (fl StdLibLogger) Error(arg0 interface{}, args ...interface{}) error

func (StdLibLogger) Fine

func (fl StdLibLogger) Fine(arg0 interface{}, args ...interface{})

func (StdLibLogger) Finest

func (fl StdLibLogger) Finest(arg0 interface{}, args ...interface{})

func (StdLibLogger) Info

func (fl StdLibLogger) Info(arg0 interface{}, args ...interface{})

func (StdLibLogger) Log

func (fl StdLibLogger) Log(lvl level, arg0 interface{}, args ...interface{}) (e error)

func (StdLibLogger) Trace

func (fl StdLibLogger) Trace(arg0 interface{}, args ...interface{})

func (StdLibLogger) Warn

func (fl StdLibLogger) Warn(arg0 interface{}, args ...interface{}) error

Directories

Path Synopsis
examples
A collection of useful RequestFilters and ResponseFilters
A collection of useful RequestFilters and ResponseFilters
Helpers for generating common types of responses
Helpers for generating common types of responses
A collection of useful Routers
A collection of useful Routers
Utilities used by falcore and its sub-packages IMPORTANT: utils cannot import falcore or there will be a circular dependency.
Utilities used by falcore and its sub-packages IMPORTANT: utils cannot import falcore or there will be a circular dependency.

Jump to

Keyboard shortcuts

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