Documentation
¶
Index ¶
- Constants
- Variables
- func ErrorWithLine(err error) error
- func Getenv(key, def string) string
- func NewErrSession(msg string) error
- func RegisterTransactionType(name string, tx Transactioner)
- func Run(config *Config) error
- type Application
- type Config
- type Context
- func (c *Context) ErrorWithLine(err error) error
- func (c *Context) Invoke(unit Unit, newFunc func(), defaultFunc func())
- func (c *Context) Redirect(url string, permanently bool) error
- func (c *Context) Render(data interface{}) error
- func (c *Context) RenderError(statusCode int, err error, data interface{}) error
- func (c *Context) RenderJSON(data interface{}) error
- func (c *Context) RenderText(content string) error
- func (c *Context) RenderXML(data interface{}) error
- func (c *Context) SendFile(path string) error
- type Controller
- type DatabaseConfig
- type DatabaseMap
- type DefaultController
- func (dc *DefaultController) DELETE(c *Context) error
- func (dc *DefaultController) GET(c *Context) error
- func (dc *DefaultController) HEAD(c *Context) error
- func (dc *DefaultController) PATCH(c *Context) error
- func (dc *DefaultController) POST(c *Context) error
- func (dc *DefaultController) PUT(c *Context) error
- type Deleter
- type DispatchMiddleware
- type ErrSession
- type ErrorController
- type Event
- type EventHandlerMap
- type Flash
- type FlashData
- type FlashMiddleware
- type FormMiddleware
- type GenmaiTransaction
- type Getter
- type Header
- type LoggerConfig
- type Middleware
- type Migration
- type PanicRecoverMiddleware
- type ParamError
- type Params
- type Patcher
- type Poster
- type Putter
- type Request
- type RequestLoggingMiddleware
- type ResourceSet
- type Response
- type Route
- type RouteTable
- type Router
- type Session
- type SessionCookieStore
- type SessionMiddleware
- type SessionStore
- type StaticServe
- type Template
- type TemplateFuncMap
- type TemplatePathInfo
- type Transactioner
- type Unit
- type Validator
Constants ¶
const ( // DefaultHttpAddr is the default listen address. DefaultHttpAddr = "127.0.0.1:9100" // DefaultMaxClientBodySize is the maximum size of HTTP request body. // This can be overridden by setting Config.MaxClientBodySize. DefaultMaxClientBodySize = 1024 * 1024 * 10 // 10MB // StaticDir is the directory of the static files. StaticDir = "public" )
const ( LayoutDir = "layout" ErrorTemplateDir = "error" )
const MigrationTableName = "schema_migration"
Variables ¶
var ( ErrInvalidFormat = errors.New("invalid format") ErrUnsupportedFieldType = errors.New("unsupported field type") )
var (
ErrInvokeDefault = errors.New("invoke default")
)
var MimeTypeFormats = mimeTypeFormats{
"application/json": "json",
"application/xml": "xml",
"text/html": "html",
"text/plain": "txt",
}
MimeTypeFormats is relation between mime type and file extension.
var TxTypeMap = make(map[string]Transactioner)
Functions ¶
func ErrorWithLine ¶ added in v0.7.0
ErrorWithLine returns error that added the filename and line to err.
func Getenv ¶ added in v0.7.0
Getenv is similar to os.Getenv. However, Getenv returns def value if the variable is not present, and sets def to environment variable.
func NewErrSession ¶
func RegisterTransactionType ¶
func RegisterTransactionType(name string, tx Transactioner)
RegisterTransactionType registers a transaction type. If already registered, it overwrites.
Types ¶
type Application ¶
type Application struct { // Config is a configuration of an application. Config *Config // Router is an HTTP request router of an application. Router *Router // Template is template sets of an application. Template *Template // Logger is an application logger. Logger log.Logger // Event is an interface of the event system. Event *Event // ResourceSet is set of resource of an application. ResourceSet ResourceSet // contains filtered or unexported fields }
Application represents a Kocha app. This implements the http.Handler interface.
func New ¶
func New(config *Config) (*Application, error)
New returns a new Application that configured by config.
func (*Application) Invoke ¶
func (app *Application) Invoke(unit Unit, newFunc func(), defaultFunc func())
Invoke invokes newFunc. It invokes newFunc but will behave to fallback. When unit.ActiveIf returns false or any errors occurred in invoking, it invoke the defaultFunc if defaultFunc isn't nil. Also if any errors occurred at least once, next invoking will always invoke the defaultFunc.
func (*Application) ServeHTTP ¶
func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler.ServeHTTP.
type Config ¶
type Config struct { Addr string // listen address, DefaultHttpAddr if empty. AppPath string // root path of the application. AppName string // name of the application. DefaultLayout string // name of the default layout. Template *Template // template config. RouteTable RouteTable // routing config. Middlewares []Middleware // middlewares. Logger *LoggerConfig // logger config. Event *Event // event config. MaxClientBodySize int64 // maximum size of request body, DefaultMaxClientBodySize if 0 ResourceSet ResourceSet }
Config represents a application-scope configuration.
type Context ¶
type Context struct { Name string // controller name. Layout string // layout name. Format string // format of response. Data interface{} // data for template. Request *Request // request. Response *Response // response. Params *Params // parameters of form values. Session Session // session. Flash Flash // flash messages. App *Application // an application. // Errors represents the map of errors that related to the form values. // A map key is field name, and value is slice of errors. // Errors will be set by Context.Params.Bind(). Errors map[string][]*ParamError }
Context represents a context of each request.
func (*Context) ErrorWithLine ¶ added in v0.7.0
ErrorWithLine returns error that added the filename and line to err.
func (*Context) Redirect ¶ added in v0.7.0
Redirect renders result of redirect.
If permanently is true, redirect to url with 301. (http.StatusMovedPermanently) Otherwise redirect to url with 302. (http.StatusFound)
func (*Context) Render ¶ added in v0.7.0
Render renders a template.
A data to used will be determined the according to the following rules.
1. If data of any map type is given, it will be merged to Context.Data if possible.
2. If data of another type is given, it will be set to Context.Data.
3. If data is nil, Context.Data as is.
Render retrieve a template file from controller name and c.Response.ContentType. e.g. If controller name is "root" and ContentType is "application/xml", Render will try to retrieve the template file "root.xml". Also ContentType set to "text/html" if not specified.
func (*Context) RenderError ¶ added in v0.7.0
RenderError renders an error page with statusCode.
RenderError is similar to Render, but there is the points where some different. If err is not nil, RenderError outputs the err to log using c.App.Logger.Error. RenderError retrieves a template file from statusCode and c.Response.ContentType. e.g. If statusCode is 500 and ContentType is "application/xml", RenderError will try to retrieve the template file "errors/500.xml". If failed to retrieve the template file, it returns result of text with statusCode. Also ContentType set to "text/html" if not specified.
func (*Context) RenderJSON ¶ added in v0.7.0
RenderJSON renders the data as JSON.
RenderJSON is similar to Render but data will be encoded to JSON. ContentType set to "application/json" if not specified.
func (*Context) RenderText ¶ added in v0.7.0
RenderText renders the content.
ContentType set to "text/plain" if not specified.
func (*Context) RenderXML ¶ added in v0.7.0
RenderXML renders the data as XML.
RenderXML is similar to Render but data will be encoded to XML. ContentType set to "application/xml" if not specified.
func (*Context) SendFile ¶ added in v0.7.0
SendFile sends a content.
The path argument specifies an absolute or relative path. If absolute path, read the content from the path as it is. If relative path, First, Try to get the content from included resources and returns it if successful. Otherwise, Add AppPath and StaticDir to the prefix of the path and then will read the content from the path that. Also, set ContentType detect from content if c.Response.ContentType is empty.
type Controller ¶
Controller is the interface that the request controller.
type DatabaseConfig ¶
type DatabaseConfig struct { // name of database driver such as "mysql". Driver string // Data Source Name. // e.g. such as "travis@/db_name". DSN string }
DatabaseConfig represents a configuration of the database.
type DatabaseMap ¶
type DatabaseMap map[string]DatabaseConfig
type DefaultController ¶
type DefaultController struct { }
DefaultController implements Controller interface. This can be used to save the trouble to implement all of the methods of Controller interface.
func (*DefaultController) DELETE ¶
func (dc *DefaultController) DELETE(c *Context) error
DELETE implements Deleter interface that renders the HTTP 405 Method Not Allowed.
func (*DefaultController) GET ¶
func (dc *DefaultController) GET(c *Context) error
GET implements Getter interface that renders the HTTP 405 Method Not Allowed.
func (*DefaultController) HEAD ¶
func (dc *DefaultController) HEAD(c *Context) error
HEAD implements Header interface that renders the HTTP 405 Method Not Allowed.
func (*DefaultController) PATCH ¶
func (dc *DefaultController) PATCH(c *Context) error
PATCH implements Patcher interface that renders the HTTP 405 Method Not Allowed.
func (*DefaultController) POST ¶
func (dc *DefaultController) POST(c *Context) error
POST implements Poster interface that renders the HTTP 405 Method Not Allowed.
func (*DefaultController) PUT ¶
func (dc *DefaultController) PUT(c *Context) error
PUT implements Putter interface that renders the HTTP 405 Method Not Allowed.
type DispatchMiddleware ¶ added in v0.7.0
type DispatchMiddleware struct{}
DispatchMiddleware is a middleware to dispatch handler. DispatchMiddleware should be set to last of middlewares because doesn't call other middlewares after DispatchMiddleware.
func (*DispatchMiddleware) Process ¶ added in v0.7.0
func (m *DispatchMiddleware) Process(app *Application, c *Context, next func() error) error
Process implements the Middleware interface.
type ErrSession ¶
type ErrSession struct {
// contains filtered or unexported fields
}
func (ErrSession) Error ¶
func (e ErrSession) Error() string
type ErrorController ¶
type ErrorController struct { *DefaultController StatusCode int }
ErrorController is generic controller for error response.
func (*ErrorController) GET ¶
func (ec *ErrorController) GET(c *Context) error
type Event ¶ added in v0.7.0
type Event struct { // HandlerMap is a map of queue/handlers. HandlerMap EventHandlerMap // WorkersPerQueue is a number of workers per queue. // The default value is taken from GOMAXPROCS. // If value of GOMAXPROCS is invalid, set to 1. WorkersPerQueue int // ErrorHandler is the handler for error. // If you want to use your own error handler, please set to ErrorHandler. ErrorHandler func(err interface{}) // contains filtered or unexported fields }
Evevnt represents the event.
type EventHandlerMap ¶ added in v0.7.0
type EventHandlerMap map[event.Queue]map[string]func(app *Application, args ...interface{}) error
EventHandlerMap represents a map of event handlers.
type Flash ¶
Flash represents a container of flash messages. Flash is for the one-time messaging between requests. It useful for implementing the Post/Redirect/Get pattern.
type FlashData ¶
type FlashData struct { Data string // flash message. Loaded bool // whether the message was loaded. }
FlashData represents a data of flash messages.
type FlashMiddleware ¶
type FlashMiddleware struct{}
Flash messages processing middleware.
func (*FlashMiddleware) Process ¶ added in v0.7.0
func (m *FlashMiddleware) Process(app *Application, c *Context, next func() error) error
type FormMiddleware ¶ added in v0.7.0
type FormMiddleware struct{}
FormMiddleware is a middleware to parse a form data from query string and/or request body.
func (*FormMiddleware) Process ¶ added in v0.7.0
func (m *FormMiddleware) Process(app *Application, c *Context, next func() error) error
Process implements the Middleware interface.
type GenmaiTransaction ¶
type GenmaiTransaction struct {
// contains filtered or unexported fields
}
GenmaiTransaction implements Transactioner interface.
func (*GenmaiTransaction) Begin ¶
func (t *GenmaiTransaction) Begin(driverName, dsn string) (tx interface{}, err error)
Begin starts a transaction of Genmai. If unsupported driver name given or any error occurred, it returns nil and error.
func (*GenmaiTransaction) Commit ¶
func (t *GenmaiTransaction) Commit() error
Commit commits the transaction of Genmai.
func (*GenmaiTransaction) ImportPath ¶
func (t *GenmaiTransaction) ImportPath() string
ImportPath returns the import path of Genmai.
func (*GenmaiTransaction) Rollback ¶
func (t *GenmaiTransaction) Rollback() error
Rollback rollbacks the transaction of Genmai.
func (*GenmaiTransaction) TransactionType ¶
func (t *GenmaiTransaction) TransactionType() interface{}
TransactionType returns the transaction type of Genmai.
type LoggerConfig ¶
type LoggerConfig struct { Writer io.Writer // output destination for the logger. Formatter log.Formatter // formatter for log entry. Level log.Level // log level. }
LoggerConfig represents the configuration of the logger.
type Middleware ¶
type Middleware interface {
Process(app *Application, c *Context, next func() error) error
}
Middleware is the interface that middleware.
type Migration ¶
type Migration struct {
// contains filtered or unexported fields
}
func Migrate ¶
func Migrate(config DatabaseConfig, m interface{}) *Migration
type PanicRecoverMiddleware ¶ added in v0.7.0
type PanicRecoverMiddleware struct{}
PanicRecoverMiddleware is a middleware to recover a panic where occurred in request sequence.
func (*PanicRecoverMiddleware) Process ¶ added in v0.7.0
func (m *PanicRecoverMiddleware) Process(app *Application, c *Context, next func() error) (err error)
type ParamError ¶
ParamError indicates that a field has error.
func NewParamError ¶
func NewParamError(name string, err error) *ParamError
NewParamError returns a new ParamError.
func (*ParamError) Error ¶
func (e *ParamError) Error() string
type Params ¶
Params represents a form values.
func (*Params) Bind ¶
Bind binds form values of fieldNames to obj. obj must be a pointer of struct. If obj isn't a pointer of struct, it returns error. Note that it in the case of errors due to a form value binding error, no error is returned. Binding errors will set to map of returned from Controller.Errors().
type Request ¶
Request represents a request.
type RequestLoggingMiddleware ¶
type RequestLoggingMiddleware struct{}
Request logging middleware.
func (*RequestLoggingMiddleware) Process ¶ added in v0.7.0
func (m *RequestLoggingMiddleware) Process(app *Application, c *Context, next func() error) error
type ResourceSet ¶
type ResourceSet map[string]interface{}
ResourceSet represents a set of pre-loaded resources.
func (*ResourceSet) Add ¶
func (rs *ResourceSet) Add(name string, data interface{})
Add adds pre-loaded resource.
func (ResourceSet) Get ¶
func (rs ResourceSet) Get(name string) interface{}
Get gets pre-loaded resource by name.
type Response ¶
type Response struct { http.ResponseWriter ContentType string StatusCode int // contains filtered or unexported fields }
Response represents a response.
type Route ¶
type Route struct { Name string Path string Controller Controller // contains filtered or unexported fields }
Route represents a route.
func (*Route) ParamNames ¶
ParamNames returns names of the path parameters.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router represents a router of kocha.
type Session ¶
Session represents a session data store.
type SessionCookieStore ¶
type SessionCookieStore struct { // key for the encryption. SecretKey string // Key for the cookie singing. SigningKey string }
Implementation of cookie store.
This session store will be a session save to client-side cookie. Session cookie for save is encoded, encrypted and signed.
func (*SessionCookieStore) Load ¶
func (store *SessionCookieStore) Load(key string) (sess Session, err error)
Load returns the session data that extract from cookie value. The key is stored session cookie value.
func (*SessionCookieStore) Save ¶
func (store *SessionCookieStore) Save(sess Session) (key string, err error)
Save saves and returns the key of session cookie. Actually, key is session cookie data itself.
func (*SessionCookieStore) Validate ¶
func (store *SessionCookieStore) Validate() error
Validate validates SecretKey size.
type SessionMiddleware ¶
type SessionMiddleware struct { // Name of cookie (key) Name string // Implementation of session store Store SessionStore // Expiration of session cookie, in seconds, from now. (not session expiration) // 0 is for persistent. CookieExpires time.Duration // Expiration of session data, in seconds, from now. (not cookie expiration) // 0 is for persistent. SessionExpires time.Duration HttpOnly bool ExpiresKey string }
SessionMiddleware is a middleware to process a session.
func (*SessionMiddleware) Process ¶ added in v0.7.0
func (m *SessionMiddleware) Process(app *Application, c *Context, next func() error) error
func (*SessionMiddleware) Validate ¶ added in v0.7.0
func (m *SessionMiddleware) Validate() error
Validate validates configuration of the session.
type SessionStore ¶
type SessionStore interface { Save(sess Session) (key string, err error) Load(key string) (sess Session, err error) }
SessionStore is the interface that session store.
type StaticServe ¶
type StaticServe struct {
*DefaultController
}
StaticServe is generic controller for serve a static file.
func (*StaticServe) GET ¶
func (ss *StaticServe) GET(c *Context) error
type Template ¶
type Template struct { PathInfo TemplatePathInfo // information of location of template paths. FuncMap TemplateFuncMap // same as template.FuncMap. LeftDelim string // left action delimiter. RightDelim string // right action delimiter. // contains filtered or unexported fields }
Template represents the templates information.
type TemplateFuncMap ¶
TemplateFuncMap is an alias of templete.FuncMap.
type TemplatePathInfo ¶
type TemplatePathInfo struct { Name string // name of the application. Paths []string // directory paths of the template files. }
TemplatePathInfo represents an information of template paths.
type Transactioner ¶
type Transactioner interface { // ImportPath returns the import path to import to use a transaction. // Usually, import path of ORM like "github.com/naoina/genmai". ImportPath() string // TransactionType returns an object of a transaction type. // Return value will only used to determine an argument type for the // methods of migration when generate the template. TransactionType() interface{} // Begin starts a transaction from driver name and data source name. Begin(driverName, dsn string) (tx interface{}, err error) // Commit commits the transaction. Commit() error // Rollback rollbacks the transaction. Rollback() error }
Transactioner is an interface for a transaction type.