webapp

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

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

Go to latest
Published: Oct 26, 2016 License: MIT Imports: 18 Imported by: 0

README

wercker status Build Status GoDoc GoCover GoReportCard

WebApp

Webapp is to simplify the setup of routing for a webapp or microservice. The routing is based on github.com/julienschmidt/httprouter with additional chaining and grouping support.

Install

go get github.com/mbict/webapp

Import

import (
    . "github.com/mbict/webapp"
)

Usage

See the test for usage

Author

Michael Boke

Documentation

Index

Constants

View Source
const (
	Production  string = "production"
	Development string = "development"
	Testing     string = "testing"
)
View Source
const ENV = "ENV"
View Source
const RequestIDHeader = "X-Request-Id"

RequestIDHeader is the name of the header used to transmit the request ID.

Variables

This section is empty.

Functions

func Env

func Env() string

func Error

func Error(ctx context.Context) error

Error retrieves the error from the context if a panic occurs and is handled by the recovery middleware the error from recovery is stored in the context if none is present this function will return a nil pointer

func ErrorStackTrace

func ErrorStackTrace(ctx context.Context) []byte

ErrorStackTrace retrieves the stack trace from the context if a panic occurs and is handled by the recovery middleware a stack trace is stored in the context

func Param

func Param(ctx context.Context, name string) string

Param picks one URL parameters stored in context by its name.

This is a shortcut for:

xmux.Params(ctx).ByName("name")

func ParamOK

func ParamOK(ctx context.Context, name string) (string, bool)

ParamOK picks one URL parameters stored in context by its name.

func Params

func Params(ctx context.Context) httprouter.Params

Params returns URL parameters stored in context

func RequestID

func RequestID(ctx context.Context) string

RequestID retreives the request id from the context

func SetEnv

func SetEnv(value string)

Types

type App

type App interface {
	RouteGroup

	MethodNotAllowed(handler ContextHandler)
	NotFound(handler ContextHandler)

	RedirectFixedPath(v bool)
	RedirectTrailingSlash(v bool)
	HandleOptions(v bool)

	ListenAndServe(addr string) error
	ListenAndServeTLS(addr, certFile, keyFile string) error
}

func New

func New() App

type Chain

type Chain []Middleware

Chain acts as a list of ContextHandler. Chain is effectively immutable:

func NewChain

func NewChain(handlers ...Middleware) Chain

NewChain creates a new chain,

func (Chain) Append

func (c Chain) Append(handlers ...Middleware) Chain

Append extends a chain, adding the specified handlers as the last ones in the request flow.

Append returns a new chain, leaving the original one untouched.

stdChain := webapp.New(m1, m2)
extChain := stdChain.Append(m3, m4)
// requests in stdChain go m1 -> m2
// requests in extChain go m1 -> m2 -> m3 -> m4

func (Chain) Extend

func (c Chain) Extend(chain Chain) Chain

Extend extends a chain by adding the specified chain as the last one in the request flow.

Extend returns a new chain, leaving the original ones untouched.

stdChain := webapp.New(m1, m2)
ext1Chain := webapp.New(m3, m4)
ext2Chain := stdChain.Extend(ext1Chain)
// requests in stdChain go  m1 -> m2
// requests in ext1Chain go m3 -> m4
// requests in ext2Chain go m1 -> m2 -> m3 -> m4

Another example:

 aHtmlAfterNosurf := webapp.New(m2)
	aHtml := webapp.New(m1, func(h http.Handler) http.Handler {
		csrf := nosurf.New(h)
		csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail))
		return csrf
	}).Extend(aHtmlAfterNosurf)
		// requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler
		// requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail

func (Chain) Then

Then chains the middleware and returns the final ContextHandler.

NewChain(m1, m2, m3).Then(h)

is equivalent to:

m1(m2(m3(h)))

When the request comes in, it will be passed to m1, then m2, then m3 and finally, the given handler (assuming every middleware calls the following one).

A chain can be safely reused by calling Then() several times.

stdStack := webapp.NewChain(ratelimitHandler, csrfHandler)
indexPipe = stdStack.Then(indexHandler)
authPipe = stdStack.Then(authHandler)

Note that the middleware handlers are called on every call to Then() and thus several instances of the same middleware will be created when a chain is reused in this way. For proper middleware, this should cause no problems.

type ContextHandler

type ContextHandler func(context.Context, http.ResponseWriter, *http.Request)

type Middleware

type Middleware func(ContextHandler) ContextHandler

func LogRequest

func LogRequest(logger *log.Logger) Middleware

LogRequest creates a request logger middleware.

func Recovery

func Recovery(errorHandler ContextHandler) Middleware

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func Timeout

func Timeout(duration time.Duration) Middleware

Timeout limits a request handler to run for max time of the duration Timeout( 15 * time.Second ) will limit the request to run no longer tan 15 seconds When the request times out, the request will send a 503 response

func UniqueRequestID

func UniqueRequestID() Middleware

RequestID is a middleware that injects a request ID into the context of each request. Retrieve it using RequestID(ctx). If the incoming request has a RequestIDHeader header then that value is used else a random value is generated.

func WrapMiddleware

func WrapMiddleware(i interface{}) Middleware

WrapMiddleware will convert default http handlers and non context aware handlers to context compatible with the chain middleware stack

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	Status() int
	Written() bool
	Size() int
}

type RouteGroup

type RouteGroup interface {
	Logger(logger *log.Logger)

	Use(middleware ...Middleware)
	With(middleware ...Middleware) RouteGroup
	Group(relativePath string, middleware ...Middleware) RouteGroup

	POST(relativePath string, handler ContextHandler)
	GET(relativePath string, handler ContextHandler)
	DELETE(relativePath string, handler ContextHandler)
	PATCH(relativePath string, handler ContextHandler)
	PUT(relativePath string, handler ContextHandler)
	OPTIONS(relativePath string, handler ContextHandler)
	HEAD(relativePath string, handler ContextHandler)
	LINK(relativePath string, handler ContextHandler)
	UNLINK(relativePath string, handler ContextHandler)

	Static(relativePath, directory string)
	StaticFile(relativePath, file string)

	Handle(httpMethod, relativePath string, handler ContextHandler)
	ServeHTTP(rw http.ResponseWriter, req *http.Request)
}

Jump to

Keyboard shortcuts

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