flotilla

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

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

Go to latest
Published: Dec 16, 2014 License: MIT Imports: 30 Imported by: 8

README

Flotilla

Build Status GoDoc Coverage Status license

A basic & extensible web framework in Go.

https://thrisp.github.io/flotilla/

Documentation

Index

Constants

View Source
const (
	ErrorTypeInternal = 1 << iota
	ErrorTypeExternal = 1 << iota
	ErrorTypeAll      = 0xffffffff
)

Variables

View Source
var (
	FlotillaPath string
)

Functions

func DefaultEngine

func DefaultEngine(a *App) error

func NewStaticor

func NewStaticor(env *Env) *staticor

func NewTemplator

func NewTemplator(env *Env) *templator

NewTemplator returns a new instance of the default Flotilla templator.

Types

type App

type App struct {
	Engine
	*Config
	*Env
	*Blueprint
	// contains filtered or unexported fields
}

The base of running a Flotilla instance is an App struct with a Name, an Env with information specific to running the App, and a chain of Blueprints

func Empty

func Empty(name string) *App

Returns an empty App instance with no configuration.

func New

func New(name string, enginefn SetEngine, conf ...Configuration) *App

Returns a new App with the provided Engine and minimum configuration.

func (*App) Blueprints

func (app *App) Blueprints() []*Blueprint

Blueprints provides a flat array of Blueprint instances attached to the App.

func (*App) Configure

func (a *App) Configure(c ...Configuration) error

Configure takes any number of Configuration functions and to run the app through.

func (*App) MergeRoutes

func (app *App) MergeRoutes(blueprint *Blueprint, routes Routes)

MergeRoutes merges the given blueprint with the given routes, by route existence.

func (*App) Mount

func (app *App) Mount(mount string, inherit bool, blueprints ...*Blueprint) error

Mount takes an unregistered blueprint, registering and mounting the routes to the provided string mount point with a copy of the blueprint. If inherit is true, the blueprint becomes a child blueprint of app.Blueprint.

func (*App) Name

func (app *App) Name() string

func (*App) RegisterBlueprints

func (app *App) RegisterBlueprints(blueprints ...*Blueprint)

RegisterBlueprints integrates the given blueprints with the App.

func (*App) Routes

func (app *App) Routes() Routes

Routes returns an array of Route instances, with all App routes from all App blueprints.

func (*App) Run

func (app *App) Run(addr string)

type AssetDirectory

type AssetDirectory struct {
	AssetFile
	ChildrenRead int
	Children     []os.FileInfo
}

func NewAssetDirectory

func NewAssetDirectory(name string, children []string, fs *AssetFS) *AssetDirectory

func (*AssetDirectory) Readdir

func (f *AssetDirectory) Readdir(count int) ([]os.FileInfo, error)

func (*AssetDirectory) Stat

func (f *AssetDirectory) Stat() (os.FileInfo, error)

type AssetFS

type AssetFS struct {
	Asset      func(string) ([]byte, error)
	AssetDir   func(string) ([]string, error)
	AssetNames func() []string
	Prefix     string
}

A pseudo-file structure constructed from functions & optional prefix Flotilla can use binary data, and is the current optimal way to define inbuilt assets for extensions. See: https://github.com/jteeuwen/go-bindata https://github.com/elazarl/go-bindata-assetfs

func (*AssetFS) GetAsset

func (fs *AssetFS) GetAsset(requested string) (http.File, error)

func (*AssetFS) HasAsset

func (fs *AssetFS) HasAsset(requested string) (string, bool)

func (*AssetFS) Open

func (fs *AssetFS) Open(name string) (http.File, error)

type AssetFile

type AssetFile struct {
	*bytes.Reader
	io.Closer
	FakeFile
}

func NewAssetFile

func NewAssetFile(name string, content []byte) *AssetFile

func (*AssetFile) Readdir

func (f *AssetFile) Readdir(count int) ([]os.FileInfo, error)

func (*AssetFile) Stat

func (f *AssetFile) Stat() (os.FileInfo, error)

type Assets

type Assets []*AssetFS

An array of AssetFS instances

func (Assets) Get

func (a Assets) Get(requested string) (http.File, error)

Return the requested asset as http.File from the AssetFS's contained in Asset, by supplying a string

func (Assets) GetByte

func (a Assets) GetByte(requested string) ([]byte, error)

type Blueprint

type Blueprint struct {
	Prefix   string
	Handlers []HandlerFunc
	// contains filtered or unexported fields
}

A Blueprint gathers any number routes around a prefix and an array of group specific handlers.

func NewBlueprint

func NewBlueprint(prefix string) *Blueprint

NewBlueprint returns a new Blueprint with the provided string prefix.

func (*Blueprint) CtxProcessor

func (b *Blueprint) CtxProcessor(name string, fn interface{})

CtxProcessors takes a name string and an interface to add a ContextProcessor to the blueprint.

func (*Blueprint) CtxProcessors

func (b *Blueprint) CtxProcessors(cp map[string]interface{})

CtxProcessors takes a map of ContextProcessors keyed by string for the blueprint.

func (*Blueprint) DELETE

func (b *Blueprint) DELETE(path string, handlers ...HandlerFunc)

func (*Blueprint) GET

func (b *Blueprint) GET(path string, handlers ...HandlerFunc)

func (*Blueprint) HEAD

func (b *Blueprint) HEAD(path string, handlers ...HandlerFunc)

func (*Blueprint) Handle

func (b *Blueprint) Handle(route *Route)

Handle registers new handlers and/or existing handlers with a constructed Route. For GET, POST, DELETE, PATCH, PUT, OPTIONS, and HEAD requests the respective shortcut functions can be used by specifying path & handlers.

func (*Blueprint) NewBlueprint

func (b *Blueprint) NewBlueprint(component string, handlers ...HandlerFunc) *Blueprint

New creates a new child Blueprint from the existing Blueprint.

func (*Blueprint) OPTIONS

func (b *Blueprint) OPTIONS(path string, handlers ...HandlerFunc)

func (*Blueprint) PATCH

func (b *Blueprint) PATCH(path string, handlers ...HandlerFunc)

func (*Blueprint) POST

func (b *Blueprint) POST(path string, handlers ...HandlerFunc)

func (*Blueprint) PUT

func (b *Blueprint) PUT(path string, handlers ...HandlerFunc)

func (*Blueprint) Register

func (b *Blueprint) Register(a *App)

Register will provide the app instance to the blueprint to finalize all deferred actions.

func (*Blueprint) STATIC

func (b *Blueprint) STATIC(path string)

STATIC adds a Static route handled by the app, based on the blueprint prefix.

func (*Blueprint) StatusHandle

func (b *Blueprint) StatusHandle(code int, handlers ...HandlerFunc)

Custom HttpStatus for the group, set and called from engine HttpStatuses

func (*Blueprint) Use

func (b *Blueprint) Use(handlers ...HandlerFunc)

Use adds any number of HandlerFunc to the Blueprint which will be run before route handlers for all Route attached to the Blueprint.

func (*Blueprint) UseAt

func (b *Blueprint) UseAt(index int, handlers ...HandlerFunc)

UseAt adds any number of HandlerFunc to the Blueprint at the given index, for when you must control the position in relation to other middleware.

type Config

type Config struct {
	Configured    bool
	Configuration []Configuration
	// contains filtered or unexported fields
}

type Configuration

type Configuration func(*App) error

A function that takes an App pointer to configure the App.

func CtxFunc

func CtxFunc(name string, fn interface{}) Configuration

CtxFunc adds a single function accessible as a Context Function.

func CtxFuncs

func CtxFuncs(fns map[string]interface{}) Configuration

CtxFuncs adds a map of functions accessible as Context Functions.

func CtxProcessor

func CtxProcessor(name string, fn interface{}) Configuration

CtxProcessor adds a single template context processor to the App primary Blueprint. This will affect all Blueprints & Routes.

func CtxProcessors

func CtxProcessors(fns map[string]interface{}) Configuration

CtxProcessors adds a map of context processors to the App primary Blueprint.

func EnvItem

func EnvItem(items ...string) Configuration

EnvItem adds strings of the form "section_label:value" or "label:value" to the Env store, bypassing and without reading a conf file.

func Mode

func Mode(mode string, value bool) Configuration

Mode takes a string for development, production, or testing to set the App mode.

func TemplateFunction

func TemplateFunction(name string, fn interface{}) Configuration

TemplateFunction passes a template function to the env for Templator use.

func TemplateFunctions

func TemplateFunctions(fns map[string]interface{}) Configuration

TemplateFunction passes a map of functions to the env for Templator use.

func Templating

func Templating(t Templator) Configuration

Templating supplies a Templator to the App.

type Ctx

type Ctx struct {
	Request *http.Request
	Session session.SessionStore
	Data    map[string]interface{}
	App     *App
	// contains filtered or unexported fields
}

Ctx is the primary context for passing & setting data between handlerfunc of a route, constructed from the *App and the app engine context data.

func (*Ctx) Abort

func (ctx *Ctx) Abort(code int)

func (*Ctx) AllFlashMessages

func (ctx *Ctx) AllFlashMessages() map[string]string

AllFlashMessages gets all flash messages set in the session.

func (*Ctx) Call

func (ctx *Ctx) Call(name string, args ...interface{}) (interface{}, error)

Calls a function with name in *Ctx.funcs passing in the given args.

func (*Ctx) Cookie

func (ctx *Ctx) Cookie(name string, value string, opts ...interface{}) error

Cookie takes a name, value and optional options(MaxAge as int, Path & Domain as string, Secure & as bool) to add a cookie to the header.

func (*Ctx) Cookies

func (ctx *Ctx) Cookies() map[string]*http.Cookie

Cookies returns a map of cookies in the request keyed by cookie name.

func (*Ctx) Copy

func (ctx *Ctx) Copy() *Ctx

Copies the Ctx with handlers set to nil.

func (*Ctx) Flash

func (ctx *Ctx) Flash(category string, message string)

Flash sets a flash message in the session with a category and a message.

func (*Ctx) FlashMessages

func (ctx *Ctx) FlashMessages(categories ...string) []string

FlashMessages gets flash messages set in the session by provided categories.

func (*Ctx) Get

func (ctx *Ctx) Get(key string) (interface{}, error)

Get returns the value for the given key or an error if nonexistent.

func (*Ctx) ModifyHeader

func (ctx *Ctx) ModifyHeader(action string, values ...[]string)

func (*Ctx) Next

func (ctx *Ctx) Next()

Executes the pending handlers in the chain inside the calling handlectx.

func (*Ctx) Push

func (ctx *Ctx) Push(fn HandlerFunc)

Push places a handlerfunc in ctx.deferred for execution after all handlersfuncs have run.

func (*Ctx) ReadCookies

func (ctx *Ctx) ReadCookies() map[string]string

func (*Ctx) Redirect

func (ctx *Ctx) Redirect(code int, location string)

Returns a HTTP redirect to the specific location, with the specified code. using the Ctx redirect function.

func (*Ctx) Release

func (ctx *Ctx) Release()

func (*Ctx) RenderTemplate

func (ctx *Ctx) RenderTemplate(name string, data interface{})

RenderTemplate renders an HTML template response with the Ctx rendertemplate function.

func (*Ctx) SecureCookie

func (ctx *Ctx) SecureCookie(name string, value string, opts ...interface{}) error

func (*Ctx) ServeFile

func (ctx *Ctx) ServeFile(f http.File)

ServesFile delivers a specified file using the Ctx servefile function.

func (*Ctx) ServePlain

func (ctx *Ctx) ServePlain(code int, data []byte)

ServePlain writes plain data into the body stream and updates the HTTP code, using the Ctx serveplain function.

func (*Ctx) Set

func (ctx *Ctx) Set(key string, item interface{})

Sets a new pair key/value in the current Ctx.

func (*Ctx) Start

func (ctx *Ctx) Start()

func (*Ctx) Status

func (ctx *Ctx) Status(code int)

func (*Ctx) UrlExternal

func (ctx *Ctx) UrlExternal(route string, params ...string) string

Provides a full, external url for the route specified using the given parameters, using the Ctx urlfor function.

func (*Ctx) UrlRelative

func (ctx *Ctx) UrlRelative(route string, params ...string) string

Provides a relative url for the route specified using the parameters specified, using the Ctx urlfor function.

func (*Ctx) WriteToHeader

func (ctx *Ctx) WriteToHeader(code int, values ...[]string)

WriteToHeader writes the specified code and values to the response Head. values are 2 string arrays indicating the key first and the value second to set in the Head.

type Current

type Current interface {
	Request() *http.Request
	Data() map[string]interface{}
	Form() url.Values
	Files() map[string][]*multipart.FileHeader
	StatusFunc() (func(int), bool)
	Writer() engine.ResponseWriter
}

The Current interface handles the information boundary between incoming engine context and flotilla context. The engine must provide a context.Context with a Value fitting this interface.

type Engine

type Engine interface {
	Take(string, string, func(context.Context))
	TakeStatus(int, func(context.Context))
	Reconfigure(func() error) error
	ServeHTTP(http.ResponseWriter, *http.Request)
}

type Env

type Env struct {
	Mode *Modes
	Store
	SessionManager *session.Manager
	Assets
	Staticor
	Templator
	// contains filtered or unexported fields
}

The App environment containing configuration variables & their store as well as other info & data relevant to the app.

func EmptyEnv

func EmptyEnv() *Env

EmptyEnv produces an Env with intialization but no configuration.

func (*Env) AddCtxFunc

func (env *Env) AddCtxFunc(name string, fn interface{}) error

AddCtxFunc adds a single Ctx function with the name string, checking that the function is a valid function returning 1 value, or 1 value and 1 error value.

func (*Env) AddCtxFuncs

func (env *Env) AddCtxFuncs(fns map[string]interface{}) error

AddCtxFuncs stores cross-handler functions in the Env as intermediate staging for later use by Ctx.

func (*Env) AddTplFunc

func (env *Env) AddTplFunc(name string, fn interface{})

AddTplFuncs adds template functions stored in the Env for use by a Templator.

func (*Env) AddTplFuncs

func (env *Env) AddTplFuncs(fns map[string]interface{})

AddTplFuncs adds template functions stored in the Env for use by a Templator.

func (*Env) BaseEnv

func (env *Env) BaseEnv()

NewEnv configures an intialized Env.

func (*Env) MergeEnv

func (env *Env) MergeEnv(other *Env)

Merges an outside env instance with the calling Env.

func (*Env) MergeStore

func (env *Env) MergeStore(other Store)

MergeStore merges a Store instance with the Env's Store, without replacement.

func (*Env) SessionInit

func (env *Env) SessionInit()

SessionInit initializes the session using the SessionManager, or default if no session manage is specified.

func (*Env) SetMode

func (env *Env) SetMode(mode string, value bool) error

SetMode sets the running mode for the App env by a string.

func (*Env) StaticDirs

func (env *Env) StaticDirs(dirs ...string) []string

A string array of static dirs set in env.Store["staticdirectories"]

func (*Env) StaticorInit

func (env *Env) StaticorInit()

func (*Env) TemplateDirs

func (env *Env) TemplateDirs(dirs ...string) []string

TemplateDirs produces a listing of templator template directories.

func (*Env) TemplatorInit

func (env *Env) TemplatorInit()

TemplatorInit sets a default templator if one is not set, and gathers template directories from all attached Flotilla envs.

type FakeFile

type FakeFile struct {
	Path string
	Dir  bool
	Len  int64
}

func (*FakeFile) IsDir

func (f *FakeFile) IsDir() bool

func (*FakeFile) ModTime

func (f *FakeFile) ModTime() time.Time

func (*FakeFile) Mode

func (f *FakeFile) Mode() os.FileMode

func (*FakeFile) Name

func (f *FakeFile) Name() string

func (*FakeFile) Size

func (f *FakeFile) Size() int64

func (*FakeFile) Sys

func (f *FakeFile) Sys() interface{}

type FlotillaError

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

func (*FlotillaError) Error

func (e *FlotillaError) Error() string

type HandlerFunc

type HandlerFunc func(*Ctx)

A HandlerFunc is any function taking a single parameter, *Ctx

type Loader

type Loader struct {
	FileExtensions []string
	// contains filtered or unexported fields
}

The default templator loader

func NewLoader

func NewLoader(env *Env) *Loader

func (*Loader) AssetTemplates

func (fl *Loader) AssetTemplates() []string

AssetTemplates returns a string array of templates in binary assets attached to the application. Iterates all assets, returns filenames matching flotilla loader valid extensions(default .html, .dji).

func (*Loader) ListTemplates

func (fl *Loader) ListTemplates() interface{}

ListTemplates returns a string array of absolute template paths for all templates dirs & assets matching valid extensions(default .html, .dji) and associated with the flotilla loader.

func (*Loader) Load

func (fl *Loader) Load(name string) (string, error)

func (*Loader) ValidExtension

func (fl *Loader) ValidExtension(ext string) bool

type Modes

type Modes struct {
	Development bool
	Production  bool
	Testing     bool
}

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	Status() int
	Size() int
	Written() bool
	WriteHeaderNow()
}

type Route

type Route struct {
	Name string
	// contains filtered or unexported fields
}

Data about a route for use & reuse within App.

func NewRoute

func NewRoute(method string, path string, static bool, handlers []HandlerFunc) *Route

NewRoute returns a new Route from a string method, a string path, a boolean indicating if the route is static, and an array of HandlerFunc

func (*Route) App

func (rt *Route) App() *App

func (*Route) CtxFuncs

func (rt *Route) CtxFuncs() map[string]interface{}

func (*Route) CtxProcessor

func (rt *Route) CtxProcessor(name string, fn interface{})

func (*Route) CtxProcessors

func (rt *Route) CtxProcessors(cp map[string]interface{})

func (*Route) Named

func (rt *Route) Named() string

Named produces a default name for the route based on path & parameters, useful to Blueprint and App, where a route is not specifically named.

func (*Route) Url

func (rt *Route) Url(params ...string) (*url.URL, error)

Url takes string parameters and applies them to a Route. First to any :parameter params, then *splat params. If any params are left over(not the case with a *splat), and the route method is GET, a query string of key=value is appended to the end of the url with arbitrarily assigned keys(e.g. value1=param) where no key is provided

e.g. r1 := NewRoute("GET", /my/:mysterious/path, false, []HandlerFunc{AHandlerFunc}) r2 := NewRoute("GET", /my/*path, false, []HandlerFunc{AHandlerFunc}) u1, _ := r1.Url("hello", "world=are" "you=there", "sayhi") u2, _ := r2.Url("hello", "world", "are" "you", "there") fmt.Printf("url1: %s\n", u1)

/my/hello/path?world=are&you=there&value3=sayhi

fmt.Printf("url2: %s\n", u2)

/my/hello/world/are/you/there

type Routes

type Routes map[string]*Route

A map of Route instances keyed by a string.

type SetEngine

type SetEngine func(*App) error

type Staticor

type Staticor interface {
	StaticDirs(...string) []string
	Exists(string, *Ctx) bool
}

type Store

type Store map[string]*StoreItem

Store is a map of StoreItem managed by App.Env, used as a store of varied configuration items that might be represented with a default and/or explicitly set value.

func (Store) LoadConfByte

func (s Store) LoadConfByte(b []byte, name string) (err error)

LoadConfByte loads a text configuration file as byte into a Store.

func (Store) LoadConfFile

func (s Store) LoadConfFile(filename string) (err error)

LoadConfFile loads a text configuration file into a Store.

type StoreItem

type StoreItem struct {
	Value string
	// contains filtered or unexported fields
}

A StoreItem contains a default string value and/or a string value.

func (StoreItem) Bool

func (si StoreItem) Bool() (bool, error)

Bool attempts to return the storeitem value as type bool

func (*StoreItem) Float

func (si *StoreItem) Float() (float64, error)

Float attempts to return the storeitem value as type float

func (*StoreItem) Int

func (si *StoreItem) Int() (int, error)

Int attempts to return the storeitem value as type int

func (*StoreItem) Int64

func (si *StoreItem) Int64() (int64, error)

Int64 attempts to return the storeitem value as type int64

func (*StoreItem) List

func (si *StoreItem) List(li ...string) []string

List updates the storeitem value to a list with the provided strings, and then returns the updated value as a string array type.

type TData

type TData map[string]interface{}

TData is a map sent to and accessible within the template, by the builtin rendertemplate function.

func TemplateData

func TemplateData(ctx *Ctx, any interface{}) TData

func (TData) CALL

func (t TData) CALL(name string) interface{}

CALL will call the context processor by name, returning an interface{} or error.

func (TData) GetFlashMessages

func (t TData) GetFlashMessages(categories ...string) []string

GetFlashMessages gets flash messages stored with TData by category.

func (TData) HTML

func (t TData) HTML(name string) template.HTML

HTML will call the context processor by name return html, html formatted error, or html formatted notice that the processor could not return an html value.

func (TData) STRING

func (t TData) STRING(name string) string

STRING will call the context processor by name, returning a string value, an error string value, or a string indicating that the processor could not return a string value.

func (TData) UrlFor

func (t TData) UrlFor(route string, external bool, params ...string) string

type Templator

type Templator interface {
	Render(io.Writer, string, interface{}) error
	ListTemplateDirs() []string
	ListTemplates() []string
	UpdateTemplateDirs(...string)
}

Templator is an interface with methods for application templating.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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