Documentation ¶
Overview ¶
cidre is a modular and extensible thin web framework in Go. http://yuin.github.io/cidre/
Index ¶
- Constants
- Variables
- func BuildString(ca int, ss ...string) string
- func DefaultLogger(level LogLevel, message string)
- func SignString(value, key string) string
- func ValidateSignedString(value, key string) (string, error)
- type App
- func (app *App) BuildUrl(n string, args ...string) string
- func (app *App) DefaultOnNotFound(w http.ResponseWriter, r *http.Request)
- func (app *App) DefaultOnPanic(w http.ResponseWriter, r *http.Request, rcv interface{})
- func (app *App) MountPoint(path string) *MountPoint
- func (app *App) Run(_server ...*http.Server)
- func (app *App) ServeHTTP(ww http.ResponseWriter, r *http.Request)
- func (app *App) Server() *http.Server
- func (app *App) Setup()
- func (app *App) Use(middlewares ...interface{})
- type AppConfig
- type BaseRenderer
- type ConfigContainer
- type ConfigMapping
- type Context
- type Dict
- func (self Dict) Copy(other map[string]interface{})
- func (self Dict) Del(key string) Dict
- func (self Dict) Get(key string) interface{}
- func (self Dict) GetBool(key string) bool
- func (self Dict) GetInt(key string) int
- func (self Dict) GetOr(key string, value interface{}) interface{}
- func (self Dict) GetString(key string) string
- func (self Dict) Has(key string) bool
- func (self Dict) Pop(key string) interface{}
- func (self Dict) Set(key string, value interface{}) Dict
- func (self Dict) Update(other map[string]interface{})
- type Hook
- type HookDirection
- type Hooks
- type HtmlTemplateRenderer
- func (rndr *HtmlTemplateRenderer) Compile()
- func (rndr *HtmlTemplateRenderer) GetLayout(name string) (string, bool)
- func (rndr *HtmlTemplateRenderer) GetTemplate(name string) (*template.Template, bool)
- func (rndr *HtmlTemplateRenderer) Html(w http.ResponseWriter, args ...interface{})
- func (rndr *HtmlTemplateRenderer) RenderTemplateFile(w io.Writer, name string, param interface{})
- func (rndr *HtmlTemplateRenderer) SetLayout(name, layout string)
- func (rndr *HtmlTemplateRenderer) SetTemplate(name string, tpl *template.Template)
- type HtmlTemplateRendererConfig
- type LogLevel
- type Logger
- type MemorySessionStore
- func (ms *MemorySessionStore) Count() int
- func (ms *MemorySessionStore) Delete(sessionId string)
- func (ms *MemorySessionStore) Exists(sessionId string) bool
- func (ms *MemorySessionStore) Gc()
- func (ms *MemorySessionStore) Init(middleware *SessionMiddleware, cfg interface{})
- func (ms *MemorySessionStore) Load(sessionId string) *Session
- func (ms *MemorySessionStore) NewSession() *Session
- func (ms *MemorySessionStore) NewSessionId() string
- func (ms *MemorySessionStore) Save(*Session)
- type Middleware
- type MiddlewareChain
- type MountPoint
- func (mt *MountPoint) Delete(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
- func (mt *MountPoint) Get(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
- func (mt *MountPoint) Post(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
- func (mt *MountPoint) Put(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
- func (mt *MountPoint) Route(n, p, m string, s bool, h http.HandlerFunc, middlewares ...interface{}) *Route
- func (mt *MountPoint) Static(n, p, local string, middlewares ...interface{}) *Route
- func (mt *MountPoint) Use(middlewares ...interface{})
- type Renderer
- type ResponseWriter
- type Route
- type Session
- type SessionConfig
- type SessionMiddleware
- type SessionStore
Constants ¶
const FlashKey = "_flash"
Variables ¶
var DynamicObjectFactory = make(dynamicObjectFactory)
DynamicObjectFactory provides functions to create an object by string name.
package mypackage type MyObject struct {} DynamicObjectFactory.Register(MyObject{}) DynamicObjectFactory.New("mypackage.MyObject")
var NopMiddleware = Middleware(MiddlewareOf(func(w http.ResponseWriter, r *http.Request) {}))
Functions ¶
func BuildString ¶
Returns a string that is the concatenation of the strings in efficient way.
func DefaultLogger ¶
func ValidateSignedString ¶
Returns a string if HMAC signature is valid.
Types ¶
type App ¶
type App struct { Config *AppConfig Routes map[string]*Route Middlewares []Middleware Logger Logger AccessLogger Logger // handlers to be called if errors was occurred during a request. OnPanic func(http.ResponseWriter, *http.Request, interface{}) // handlers to be called if no suitable routes found. OnNotFound func(http.ResponseWriter, *http.Request) Renderer Renderer Hooks Hooks // contains filtered or unexported fields }
App represents a web application. Hooks:
- setup(nil, nil, self)
- start_server(nil, nil, self)
- start_request(http.ResponseWriter, *http.Request, nil)
- start_action(http.ResponseWriter, *http.Request, nil)
- end_action(http.ResponseWriter, *http.Request, nil)
- end_request(http.ResponseWriter, *http.Request, nil)
func (*App) DefaultOnNotFound ¶
func (app *App) DefaultOnNotFound(w http.ResponseWriter, r *http.Request)
func (*App) DefaultOnPanic ¶
func (app *App) DefaultOnPanic(w http.ResponseWriter, r *http.Request, rcv interface{})
func (*App) MountPoint ¶
func (app *App) MountPoint(path string) *MountPoint
Returns a new MountPoint object associated the given path.
type AppConfig ¶
type AppConfig struct { // default : false Debug bool // Server address, default:"127.0.0.1:8080" Addr string // default: "" TemplateDirectory string // default: true, if this value is true, cidre will treat a "_method" parameter as a HTTP method name. AllowHttpMethodOverwrite bool // cidre uses text/template to format access logs. // default: "{{.c.Id}} {{.req.RemoteAddr}} {{.req.Method}} {{.req.RequestURI}} {{.req.Proto}} {{.res.Status}} {{.res.ContentLength}} {{.c.ResponseTime}}" AccessLogFormat string // default: 180s ReadTimeout time.Duration // default: 180s WriteTimeout time.Duration // default: 8192 MaxHeaderBytes int // default: false KeepAlive bool // calls runtime.GOMAXPROCS(runtime.NumCPU()) when server starts if AutoMaxProcs is true. // default: true AutoMaxProcs bool }
AppConfig is a configuration object for the App struct.
func DefaultAppConfig ¶
Returns a new AppConfig object that has default values set. If an 'init' function object argument is not nil, this function will call the function with the AppConfig object.
type BaseRenderer ¶
type BaseRenderer struct{}
func (*BaseRenderer) Json ¶
func (rndr *BaseRenderer) Json(w http.ResponseWriter, args ...interface{})
Json(w http.ResponseWriter, object interface{})
func (*BaseRenderer) Text ¶
func (rndr *BaseRenderer) Text(w http.ResponseWriter, args ...interface{})
Text(w http.ResponseWriter, format string, formatargs ...interface{})
func (*BaseRenderer) Xml ¶
func (rndr *BaseRenderer) Xml(w http.ResponseWriter, args ...interface{})
Xml(w http.ResponseWriter, object interface{})
type ConfigContainer ¶
ConfigContainer represents a section in configuration files.
func ParseIniFile ¶
func ParseIniFile(filepath string, mappings ...ConfigMapping) (ConfigContainer, error)
Attempts to read and parse the given filepath, Mapping sections to the given object. Configuration file format is simplified ini format.
Example:
[section1] ; string value: no multiline string support Key1 = String value ; bool value Key2 = true ; int value Key3 = 9999 ; float value Key3 = 99.99 ; time.Duration value Key3 = 180s [section2] ; blah-blah-blah
func (ConfigContainer) Mapping ¶
func (cc ConfigContainer) Mapping(section string, sdata interface{})
type ConfigMapping ¶
type ConfigMapping struct { Section string Struct interface{} }
type Context ¶
type Context struct { Dict App *App Session *Session Id string Route *Route PathParams *url.Values StartedAt time.Time ResponseTime time.Duration MiddlewareChain *MiddlewareChain }
Context is a per-request context object. It allows us to share variables between middlewares.
func NewContext ¶
Returns a new Context object.
func RequestContext ¶
Returns a contenxt object associated with the given request.
func (*Context) IsDynamicRoute ¶
Returns true if the matched route is dynamic, false if there is no matched routes or the matched route is for static files.
type Hook ¶
type Hook func(http.ResponseWriter, *http.Request, interface{})
Hook is a mechanism for customization of cidre. Hook is a function, to be called on some well-defined occasion.
type HookDirection ¶
type HookDirection int
HookDirection represents execution order of Hooks.
const ( // from front to back HookDirectionNormal HookDirection = iota // from back to front HookDirectionReverse )
type Hooks ¶
Hooks is a container of Hook objects.
func (Hooks) Run ¶
func (hooks Hooks) Run(name string, direction HookDirection, w http.ResponseWriter, r *http.Request, data interface{})
Executes hooks associated with the given name.
type HtmlTemplateRenderer ¶
type HtmlTemplateRenderer struct { BaseRenderer Config *HtmlTemplateRendererConfig // contains filtered or unexported fields }
Renderer interface implementation using an html/template module. HtmlTemplateRenderer loads files matches '*.tpl' recurcively.
./templates | |- layout | | | |- main_layout.tpl | |- admin_layout.tpl | |- page1.tpl |- page2.tpl
HtmlTemplateRenderer supports layout by providing an `yield` pipeline.
page1.tpl
{{/* extends main_layout */}} <div>content</div>
main_layout.tpl
<html><body> {{ yield }} </body></html>
An `include` pileline is like an html/template's `template` pipeline, but it accepts "name" parameter dynamically.
page1.tpl
<div>content</div> {{ include .SubContents . }}
func NewHtmlTemplateRenderer ¶
func NewHtmlTemplateRenderer(config *HtmlTemplateRendererConfig) *HtmlTemplateRenderer
func (*HtmlTemplateRenderer) Compile ¶
func (rndr *HtmlTemplateRenderer) Compile()
func (*HtmlTemplateRenderer) GetLayout ¶
func (rndr *HtmlTemplateRenderer) GetLayout(name string) (string, bool)
func (*HtmlTemplateRenderer) GetTemplate ¶
func (rndr *HtmlTemplateRenderer) GetTemplate(name string) (*template.Template, bool)
func (*HtmlTemplateRenderer) Html ¶
func (rndr *HtmlTemplateRenderer) Html(w http.ResponseWriter, args ...interface{})
func (*HtmlTemplateRenderer) RenderTemplateFile ¶
func (rndr *HtmlTemplateRenderer) RenderTemplateFile(w io.Writer, name string, param interface{})
func (*HtmlTemplateRenderer) SetLayout ¶
func (rndr *HtmlTemplateRenderer) SetLayout(name, layout string)
func (*HtmlTemplateRenderer) SetTemplate ¶
func (rndr *HtmlTemplateRenderer) SetTemplate(name string, tpl *template.Template)
type HtmlTemplateRendererConfig ¶
type HtmlTemplateRendererConfig struct { TemplateDirectory string LeftDelim string RightDelim string FuncMap template.FuncMap }
HtmlTemplateRendererConfig is a configuration object for the HtmlTemplateRenderer
func DefaultHtmlTemplateRendererConfig ¶
func DefaultHtmlTemplateRendererConfig(init ...func(*HtmlTemplateRendererConfig)) *HtmlTemplateRendererConfig
Returns a HtmlTemplateRendererConfig object that has default values set. If an 'init' function object argument is not nil, this function will call the function with the HtmlTemplateRendererConfig object.
type MemorySessionStore ¶
func (*MemorySessionStore) Count ¶
func (ms *MemorySessionStore) Count() int
func (*MemorySessionStore) Delete ¶
func (ms *MemorySessionStore) Delete(sessionId string)
func (*MemorySessionStore) Exists ¶
func (ms *MemorySessionStore) Exists(sessionId string) bool
func (*MemorySessionStore) Gc ¶
func (ms *MemorySessionStore) Gc()
func (*MemorySessionStore) Init ¶
func (ms *MemorySessionStore) Init(middleware *SessionMiddleware, cfg interface{})
func (*MemorySessionStore) Load ¶
func (ms *MemorySessionStore) Load(sessionId string) *Session
func (*MemorySessionStore) NewSession ¶
func (ms *MemorySessionStore) NewSession() *Session
func (*MemorySessionStore) NewSessionId ¶
func (ms *MemorySessionStore) NewSessionId() string
func (*MemorySessionStore) Save ¶
func (ms *MemorySessionStore) Save(*Session)
type Middleware ¶
Middleware is an ailias for the http.Handler interface. In ServeHTTP, you should yield to the next middleware in the chain.
func MiddlewareOf ¶
func MiddlewareOf(arg interface{}) Middleware
func MiddlewaresOf ¶
func MiddlewaresOf(args ...interface{}) []Middleware
type MiddlewareChain ¶
type MiddlewareChain struct {
// contains filtered or unexported fields
}
MiddlewareChain represents an invocation chain of a middleware. Middlewares use the MiddlewareChain to invoke the next middleware in the chain, or if the calling middleware is the last middleware in the chain, to invoke the handler at the end of the chain.
func NewMiddlewareChain ¶
func NewMiddlewareChain(middlewares []Middleware) *MiddlewareChain
Returns a new MiddlewareChain object.
func (*MiddlewareChain) Copy ¶
func (mc *MiddlewareChain) Copy() *MiddlewareChain
Returns a copy of the MiddlewareChain object.
func (*MiddlewareChain) DoNext ¶
func (mc *MiddlewareChain) DoNext(w http.ResponseWriter, r *http.Request)
Causes the next middleware in the chain to be invoked, or if the calling middleware is the last middleware in the chain, causes the handler at the end of the chain to be invoked.
type MountPoint ¶
type MountPoint struct { App *App Path string Middlewares []Middleware }
MountPoint represents a group of routes that has same URL prefix and a set of middlewares.
func (*MountPoint) Delete ¶
func (mt *MountPoint) Delete(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
Shortcut for Route(name, pattern, "DELETE", false, handler, ...Middleware)
func (*MountPoint) Get ¶
func (mt *MountPoint) Get(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
Shortcut for Route(name, pattern, "GET", false, handler, ...Middleware)
func (*MountPoint) Post ¶
func (mt *MountPoint) Post(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
Shortcut for Route(name, pattern, "POST", false, handler, ...Middleware)
func (*MountPoint) Put ¶
func (mt *MountPoint) Put(n, p string, h http.HandlerFunc, middlewares ...interface{}) *Route
Shortcut for Route(name, pattern, "Put", false, handler, ...Middleware)
func (*MountPoint) Route ¶
func (mt *MountPoint) Route(n, p, m string, s bool, h http.HandlerFunc, middlewares ...interface{}) *Route
Registers a http.HandlerFunc and middlewares with the given path pattern and method.
func (*MountPoint) Static ¶
func (mt *MountPoint) Static(n, p, local string, middlewares ...interface{}) *Route
Registers a handler that serves static files.
func (*MountPoint) Use ¶
func (mt *MountPoint) Use(middlewares ...interface{})
Adds a middleware to the end of the middleware chain.
type Renderer ¶
type Renderer interface { // Compiles and caches template files Compile() // Renders a template file specified by the given name RenderTemplateFile(io.Writer, string, interface{}) // Writes the contents and the Content-Type header to the http.ResponseWriter. Html(http.ResponseWriter, ...interface{}) // Writes the contents and the Content-Type header to the http.ResponseWriter. Json(http.ResponseWriter, ...interface{}) // Writes the contents and the Content-Type header to the http.ResponseWriter. Xml(http.ResponseWriter, ...interface{}) // Writes the contents and the Content-Type header to the http.ResponseWriter. Text(http.ResponseWriter, ...interface{}) }
Renderer provides easy way to serialize objects and render template files.
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter SetHeader(int) ContentLength() int Status() int Hooks() Hooks }
ResponseWriter is a wrapper around http.ResponseWriter that provides extra methods about the response.
Hook points:
- before_write_header(self, nil, status int)
- after_write_header(self, nil, status int)
- before_write_content(self, nil, content []byte)
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) ResponseWriter
Returns a new ResponseWriter object wrap around the given http.ResponseWriter object.
type Route ¶
type Route struct { Name string PathParamNames []string Method string Pattern *regexp.Regexp PatternString string IsStatic bool MiddlewareChain *MiddlewareChain Meta Dict }
Route represents a Route in cidre. Route implements the Middleware interface.
type Session ¶
Session value container.
func NewSession ¶
func (*Session) Flashes ¶
Returns a list of flash messages from the session.
session.AddFlash("info", "info message1") session.AddFlash("info", "info message2") session.AddFlash("error", "error message") messages := session.Flashes() // -> {"info":["info message1", "info message2"], "error":["error message"]}
func (*Session) UpdateLastAccessTime ¶
func (sess *Session) UpdateLastAccessTime()
type SessionConfig ¶
type SessionConfig struct { // default: gossessionid CookieName string CookieDomain string // default: false CookieSecure bool CookiePath string CookieExpires time.Duration // A term used to authenticate the cookie value using HMAC Secret string // default: "cidre.MemorySessionStore" SessionStore string // default: 30m GcInterval time.Duration // default: 30m LifeTime time.Duration }
SessionConfig is a configuration object for the SessionMiddleware
func DefaultSessionConfig ¶
func DefaultSessionConfig(init ...func(*SessionConfig)) *SessionConfig
Returns a SessionConfig object that has default values set. If an 'init' function object argument is not nil, this function will call the function with the SessionConfig object.
type SessionMiddleware ¶
type SessionMiddleware struct { Config *SessionConfig Store SessionStore // contains filtered or unexported fields }
Middleware for session management.
func NewSessionMiddleware ¶
func NewSessionMiddleware(app *App, config *SessionConfig, storeConfig interface{}) *SessionMiddleware
Returns a new SessionMiddleware object.
func (*SessionMiddleware) Gc ¶
func (sm *SessionMiddleware) Gc()
func (*SessionMiddleware) ServeHTTP ¶
func (sm *SessionMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)
type SessionStore ¶
type SessionStore interface { Lock() Unlock() Init(*SessionMiddleware, interface{}) Exists(string) bool NewSession() *Session Save(*Session) Load(string) *Session Delete(string) Gc() Count() int }
SessionStore is an interface for custom session stores. See the MemorySessionStore for examples.