cidre: github.com/yuin/cidre Index | Files

package cidre

import "github.com/yuin/cidre"

cidre is a modular and extensible thin web framework in Go. http://yuin.github.io/cidre/

Index

Package Files

app.go config.go doc.go renderer.go session.go utils.go

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) {}))

func BuildString Uses

func BuildString(ca int, ss ...string) string

Returns a string that is the concatenation of the strings in efficient way.

func DefaultLogger Uses

func DefaultLogger(level LogLevel, message string)

func MiddlewaresOf Uses

func MiddlewaresOf(args ...interface{}) []Middleware

func SignString Uses

func SignString(value, key string) string

Returns a string with a HMAC signature.

func ValidateSignedString Uses

func ValidateSignedString(value, key string) (string, error)

Returns a string if HMAC signature is valid.

type App Uses

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 NewApp Uses

func NewApp(config *AppConfig) *App

Returns a new App object.

func (*App) BuildUrl Uses

func (app *App) BuildUrl(n string, args ...string) string

Builds an url for the given named route with path parameters.

func (*App) DefaultOnNotFound Uses

func (app *App) DefaultOnNotFound(w http.ResponseWriter, r *http.Request)

func (*App) DefaultOnPanic Uses

func (app *App) DefaultOnPanic(w http.ResponseWriter, r *http.Request, rcv interface{})

func (*App) MountPoint Uses

func (app *App) MountPoint(path string) *MountPoint

Returns a new MountPoint object associated the given path.

func (*App) Run Uses

func (app *App) Run(_server ...*http.Server)

Run the http.Server. If _server is not passed, App.Server() will be used as a http.Server object.

func (*App) ServeHTTP Uses

func (app *App) ServeHTTP(ww http.ResponseWriter, r *http.Request)

func (*App) Server Uses

func (app *App) Server() *http.Server

Returns a new http.Server object.

func (*App) Setup Uses

func (app *App) Setup()

func (*App) Use Uses

func (app *App) Use(middlewares ...interface{})

Adds a middleware to the end of the middleware chain.

type AppConfig Uses

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 Uses

func DefaultAppConfig(init ...func(*AppConfig)) *AppConfig

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 Uses

type BaseRenderer struct{}

func (*BaseRenderer) Json Uses

func (rndr *BaseRenderer) Json(w http.ResponseWriter, args ...interface{})

Json(w http.ResponseWriter, object interface{})

func (*BaseRenderer) Text Uses

func (rndr *BaseRenderer) Text(w http.ResponseWriter, args ...interface{})

Text(w http.ResponseWriter, format string, formatargs ...interface{})

func (*BaseRenderer) Xml Uses

func (rndr *BaseRenderer) Xml(w http.ResponseWriter, args ...interface{})

Xml(w http.ResponseWriter, object interface{})

type ConfigContainer Uses

type ConfigContainer map[string]map[string]interface{}

ConfigContainer represents a section in configuration files.

func ParseIniFile Uses

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 Uses

func (cc ConfigContainer) Mapping(section string, sdata interface{})

type ConfigMapping Uses

type ConfigMapping struct {
    Section string
    Struct  interface{}
}

type Context Uses

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 Uses

func NewContext(app *App, id string, r *http.Request) *Context

Returns a new Context object.

func RequestContext Uses

func RequestContext(r *http.Request) *Context

Returns a contenxt object associated with the given request.

func (*Context) IsDynamicRoute Uses

func (ctx *Context) IsDynamicRoute() bool

Returns true if the matched route is dynamic, false if there is no matched routes or the matched route is for static files.

type Dict Uses

type Dict map[string]interface{}

Dict is a Python's dict like object.

func NewDict Uses

func NewDict() Dict

func (Dict) Copy Uses

func (self Dict) Copy(other map[string]interface{})

func (Dict) Del Uses

func (self Dict) Del(key string) Dict

func (Dict) Get Uses

func (self Dict) Get(key string) interface{}

func (Dict) GetBool Uses

func (self Dict) GetBool(key string) bool

func (Dict) GetInt Uses

func (self Dict) GetInt(key string) int

func (Dict) GetOr Uses

func (self Dict) GetOr(key string, value interface{}) interface{}

func (Dict) GetString Uses

func (self Dict) GetString(key string) string

func (Dict) Has Uses

func (self Dict) Has(key string) bool

func (Dict) Pop Uses

func (self Dict) Pop(key string) interface{}

func (Dict) Set Uses

func (self Dict) Set(key string, value interface{}) Dict

func (Dict) Update Uses

func (self Dict) Update(other map[string]interface{})

type Hook Uses

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 Uses

type HookDirection int

HookDirection represents execution order of Hooks.

const (
    // from front to back
    HookDirectionNormal HookDirection = iota
    // from back to front
    HookDirectionReverse
)

type Hooks Uses

type Hooks map[string][]Hook

Hooks is a container of Hook objects.

func (Hooks) Add Uses

func (hooks Hooks) Add(name string, hook Hook)

Registers a hook to be executed at the given hook point.

func (Hooks) Run Uses

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 Uses

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 Uses

func NewHtmlTemplateRenderer(config *HtmlTemplateRendererConfig) *HtmlTemplateRenderer

func (*HtmlTemplateRenderer) Compile Uses

func (rndr *HtmlTemplateRenderer) Compile()

func (*HtmlTemplateRenderer) GetLayout Uses

func (rndr *HtmlTemplateRenderer) GetLayout(name string) (string, bool)

func (*HtmlTemplateRenderer) GetTemplate Uses

func (rndr *HtmlTemplateRenderer) GetTemplate(name string) (*template.Template, bool)

func (*HtmlTemplateRenderer) Html Uses

func (rndr *HtmlTemplateRenderer) Html(w http.ResponseWriter, args ...interface{})

func (*HtmlTemplateRenderer) RenderTemplateFile Uses

func (rndr *HtmlTemplateRenderer) RenderTemplateFile(w io.Writer, name string, param interface{})

func (*HtmlTemplateRenderer) SetLayout Uses

func (rndr *HtmlTemplateRenderer) SetLayout(name, layout string)

func (*HtmlTemplateRenderer) SetTemplate Uses

func (rndr *HtmlTemplateRenderer) SetTemplate(name string, tpl *template.Template)

type HtmlTemplateRendererConfig Uses

type HtmlTemplateRendererConfig struct {
    TemplateDirectory string
    LeftDelim         string
    RightDelim        string
    FuncMap           template.FuncMap
}

HtmlTemplateRendererConfig is a configuration object for the HtmlTemplateRenderer

func DefaultHtmlTemplateRendererConfig Uses

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 LogLevel Uses

type LogLevel int
const (
    LogLevelUnknown LogLevel = iota
    LogLevelDebug
    LogLevelInfo
    LogLevelWarn
    LogLevelError
    LogLevelCrit
)

func (LogLevel) String Uses

func (ll LogLevel) String() string

type Logger Uses

type Logger func(LogLevel, string)

type MemorySessionStore Uses

type MemorySessionStore struct {
    sync.Mutex
    // contains filtered or unexported fields
}

func (*MemorySessionStore) Count Uses

func (ms *MemorySessionStore) Count() int

func (*MemorySessionStore) Delete Uses

func (ms *MemorySessionStore) Delete(sessionId string)

func (*MemorySessionStore) Exists Uses

func (ms *MemorySessionStore) Exists(sessionId string) bool

func (*MemorySessionStore) Gc Uses

func (ms *MemorySessionStore) Gc()

func (*MemorySessionStore) Init Uses

func (ms *MemorySessionStore) Init(middleware *SessionMiddleware, cfg interface{})

func (*MemorySessionStore) Load Uses

func (ms *MemorySessionStore) Load(sessionId string) *Session

func (*MemorySessionStore) NewSession Uses

func (ms *MemorySessionStore) NewSession() *Session

func (*MemorySessionStore) NewSessionId Uses

func (ms *MemorySessionStore) NewSessionId() string

func (*MemorySessionStore) Save Uses

func (ms *MemorySessionStore) Save(*Session)

type Middleware Uses

type Middleware http.Handler

Middleware is an ailias for the http.Handler interface. In ServeHTTP, you should yield to the next middleware in the chain.

func MiddlewareOf Uses

func MiddlewareOf(arg interface{}) Middleware

type MiddlewareChain Uses

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 Uses

func NewMiddlewareChain(middlewares []Middleware) *MiddlewareChain

Returns a new MiddlewareChain object.

func (*MiddlewareChain) Copy Uses

func (mc *MiddlewareChain) Copy() *MiddlewareChain

Returns a copy of the MiddlewareChain object.

func (*MiddlewareChain) DoNext Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (mt *MountPoint) Static(n, p, local string, middlewares ...interface{}) *Route

Registers a handler that serves static files.

func (*MountPoint) Use Uses

func (mt *MountPoint) Use(middlewares ...interface{})

Adds a middleware to the end of the middleware chain.

type Renderer Uses

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 Uses

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 Uses

func NewResponseWriter(w http.ResponseWriter) ResponseWriter

Returns a new ResponseWriter object wrap around the given http.ResponseWriter object.

type Route Uses

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.

func NewRoute Uses

func NewRoute(n, p, m string, s bool, handler http.Handler, middlewares ...Middleware) *Route

func (*Route) ServeHTTP Uses

func (route *Route) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Session Uses

type Session struct {
    Dict
    Killed         bool
    Id             string
    LastAccessTime time.Time
}

Session value container.

func NewSession Uses

func NewSession(id string) *Session

func (*Session) AddFlash Uses

func (sess *Session) AddFlash(category string, message string)

Adds a flash message to the session

func (*Session) Flash Uses

func (sess *Session) Flash(category string) []string

Returns a flash message associated with the given category.

func (*Session) Flashes Uses

func (sess *Session) Flashes() map[string][]string

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) Kill Uses

func (sess *Session) Kill()

func (*Session) UpdateLastAccessTime Uses

func (sess *Session) UpdateLastAccessTime()

type SessionConfig Uses

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 Uses

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 Uses

type SessionMiddleware struct {
    Config *SessionConfig
    Store  SessionStore
    // contains filtered or unexported fields
}

Middleware for session management.

func NewSessionMiddleware Uses

func NewSessionMiddleware(app *App, config *SessionConfig, storeConfig interface{}) *SessionMiddleware

Returns a new SessionMiddleware object.

func (*SessionMiddleware) Gc Uses

func (sm *SessionMiddleware) Gc()

func (*SessionMiddleware) ServeHTTP Uses

func (sm *SessionMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type SessionStore Uses

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.

Package cidre imports 25 packages (graph) and is imported by 1 packages. Updated 2016-07-29. Refresh now. Tools for package owners.