cidre

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

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

Go to latest
Published: Jul 7, 2015 License: MIT Imports: 25 Imported by: 2

README

cidre GoDoc

cidre is a modular and extensible thin web framework in Go.

package main

import (
  "github.com/yuin/cidre"
  "net/http"
)

func main() {
    app := cidre.NewApp(cidre.DefaultAppConfig())
    root := app.MountPoint("/")

    root.Get("show_welcome", "wellcome", func(w http.ResponseWriter, r *http.Request) {
        app.Renderer.Text(w, "Welcome!")
    })

    app.Run()
}

How to Install

go get github.com/yuin/cidre

Routing

app := cidre.NewApp(cidre.DefaultAppConfig())
app.Use(cidre.NewSessionMiddleware(app, sessionConfig, nil))

root := app.MountPoint("/")
root.Get("show_profile", "users/(?P<name>\w+)", func(w http.ResponseWriter, r *http.Request) {
  ctx := cidre.RequestContext(r)
  ctx.PathParams.Get("name")
  app.BuildUrl("show_profile", "alice") 
  // -> /users/alice
})

Middleware

app := cidre.NewApp(cidre.DefaultAppConfig())
app.Use(cidre.NewSessionMiddleware(app, sessionConfig, nil))

root := app.MountPoint("/")
root.Use(func(w http.ResponseWriter, r *http.Request){
  // do something

  cidre.RequestContext(r).MiddlewareChain.DoNext(w,r)

  // do something
})

HTML rendering

appconfig := cidre.DefaultAppConfig())
appconfig.TemplateDirectory = "./templates"
app := cidre.NewApp(appconfig)

root := app.MountPoint("/")
root.Get("page", "page", func(w http.ResponseWriter, r *http.Request) {
  view := cidre.Dict{"key":"value"}
  app.Renderer.Html(w, "template_name", view)
})

Sessions

app := cidre.NewApp(cidre.DefaultAppConfig())
sessionConfig := cidre.DefaultSessionConfig()
app.Use(cidre.NewSessionMiddleware(app, sessionConfig, nil))

root := app.MountPoint("/")
root.Get("page", "page", func(w http.ResponseWriter, r *http.Request) {
  ctx := cidre.RequestContext(r)
  ctx.Session.Set("key", "value")
  ctx.Session.Get("key")
  ctx.Session.AddFlash("info", "info message")
})

Loading configuration files

app.ini:

[cidre]
Addr = 127.0.0.1:8080

[session.base]
CookieName = sessionid
Secret = some very secret

code:

appConfig := cidre.DefaultAppConfig()
sessionConfig := cidre.DefaultSessionConfig()
_, err := cidre.ParseIniFile("app.ini",
	cidre.ConfigMapping{"cidre", appConfig},
	cidre.ConfigMapping{"session.base", sessionConfig},
)
if err != nil {
	panic(err)
}
app := cidre.NewApp(appConfig)

Hooks

cidre.App and cidre.ResponseWriter has some hook points. See godoc for details.

app := cidre.NewApp(cidre.DefaultAppConfig())
app.Hooks.Add("start_request", func(w http.ResponseWriter, r *http.Request, data interface{}) {
	w.Header().Add("X-Server", "Go")
})

root := app.MountPoint("/")
root.Use(func(w http.ResponseWriter, r *http.Request){

   w.(cidre.ResponseWriter).Hooks().Add("before_write_content", func(w http.ResponseWriter, rnil *http.Request, datanil interface{}) {
      // do some stuff
   })

  cidre.RequestContext(r).MiddlewareChain.DoNext(w,r)

})

Documentation

Overview

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

Index

Constants

View Source
const FlashKey = "_flash"

Variables

View Source
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")
View Source
var NopMiddleware = Middleware(MiddlewareOf(func(w http.ResponseWriter, r *http.Request) {}))

Functions

func BuildString

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

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

func DefaultLogger

func DefaultLogger(level LogLevel, message string)

func SignString

func SignString(value, key string) string

Returns a string with a HMAC signature.

func ValidateSignedString

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

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 NewApp

func NewApp(config *AppConfig) *App

Returns a new App object.

func (*App) BuildUrl

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

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

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.

func (*App) Run

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

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

func (*App) Server

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

Returns a new http.Server object.

func (*App) Setup

func (app *App) Setup()

func (*App) Use

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

Adds a middleware to the end of the middleware chain.

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

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

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

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

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

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

Returns a new Context object.

func RequestContext

func RequestContext(r *http.Request) *Context

Returns a contenxt object associated with the given request.

func (*Context) IsDynamicRoute

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

type Dict map[string]interface{}

Dict is a Python's dict like object.

func NewDict

func NewDict() Dict

func (Dict) Copy

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

func (Dict) Del

func (self Dict) Del(key string) Dict

func (Dict) Get

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

func (Dict) GetBool

func (self Dict) GetBool(key string) bool

func (Dict) GetInt

func (self Dict) GetInt(key string) int

func (Dict) GetOr

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

func (Dict) GetString

func (self Dict) GetString(key string) string

func (Dict) Has

func (self Dict) Has(key string) bool

func (Dict) Pop

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

func (Dict) Set

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

func (Dict) Update

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

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

type Hooks map[string][]Hook

Hooks is a container of Hook objects.

func (Hooks) Add

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

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

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 LogLevel

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

func (LogLevel) String

func (ll LogLevel) String() string

type Logger

type Logger func(LogLevel, string)

type MemorySessionStore

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

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

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

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.

func NewRoute

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

func (*Route) ServeHTTP

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

type Session

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

Session value container.

func NewSession

func NewSession(id string) *Session

func (*Session) AddFlash

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

Adds a flash message to the session

func (*Session) Flash

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

Returns a flash message associated with the given category.

func (*Session) Flashes

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

func (sess *Session) Kill()

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.

Directories

Path Synopsis
_examples
wiki
cidre sample: simple wiki app
cidre sample: simple wiki app
wiki_db
cidre sample: simple wiki app
cidre sample: simple wiki app

Jump to

Keyboard shortcuts

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