kocha

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2015 License: MIT Imports: 39 Imported by: 3

README

Kocha Build Status

A convenient web application framework for Go

NOTE: Kocha is still under development, so API might be changed in future. If you still want to use the current version of Kocha, use of a version control such as gopkg.in is highly recommended.

Features

  • Batteries included
  • All configurations are in Go's syntax
  • Generate an All-In-One binary
  • Compatible with net/http

Requirement

  • Go 1.3 or later

Getting started

  1. install the framework:

     go get -u github.com/naoina/kocha
    

    And command-line tool

     go get -u github.com/naoina/kocha/cmd/...
    
  2. Create a new application:

     kocha new myapp
    

    Where "myapp" is the application name.

  3. Change directory and run the application:

     cd myapp
     kocha run
    

    or

     cd myapp
     go build -o myapp
     ./myapp
    

Documentation

See http://naoina.github.io/kocha/ for more information.

License

Kocha is licensed under the MIT

Documentation

Index

Constants

View Source
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"
)
View Source
const (
	LayoutDir        = "layout"
	ErrorTemplateDir = "error"
)
View Source
const MigrationTableName = "schema_migration"

Variables

View Source
var (
	ErrInvalidFormat        = errors.New("invalid format")
	ErrUnsupportedFieldType = errors.New("unsupported field type")
)
View Source
var (
	ErrInvokeDefault = errors.New("invoke default")
)
View Source
var MimeTypeFormats = mimeTypeFormats{
	"application/json": "json",
	"application/xml":  "xml",
	"text/html":        "html",
	"text/plain":       "txt",
}

MimeTypeFormats is relation between mime type and file extension.

View Source
var TxTypeMap = make(map[string]Transactioner)

Functions

func ErrorWithLine added in v0.7.0

func ErrorWithLine(err error) error

ErrorWithLine returns error that added the filename and line to err.

func Getenv added in v0.7.0

func Getenv(key, def string) string

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 NewErrSession(msg string) error

func RegisterTransactionType

func RegisterTransactionType(name string, tx Transactioner)

RegisterTransactionType registers a transaction type. If already registered, it overwrites.

func Run

func Run(config *Config) error

Run starts Kocha app. This will launch the HTTP server by using github.com/naoina/miyabi. If you want to use other HTTP server that compatible with net/http such as http.ListenAndServe, you can use New.

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

func (c *Context) ErrorWithLine(err error) error

ErrorWithLine returns error that added the filename and line to err.

func (*Context) Invoke

func (c *Context) Invoke(unit Unit, newFunc func(), defaultFunc func())

Invoke is shorthand of c.App.Invoke.

func (*Context) Redirect added in v0.7.0

func (c *Context) Redirect(url string, permanently bool) error

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

func (c *Context) Render(data interface{}) error

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

func (c *Context) RenderError(statusCode int, err error, data interface{}) error

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

func (c *Context) RenderJSON(data interface{}) error

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

func (c *Context) RenderText(content string) error

RenderText renders the content.

ContentType set to "text/plain" if not specified.

func (*Context) RenderXML added in v0.7.0

func (c *Context) RenderXML(data interface{}) error

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

func (c *Context) SendFile(path string) error

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

type Controller interface {
	Getter
	Poster
	Putter
	Deleter
	Header
	Patcher
}

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 Deleter

type Deleter interface {
	DELETE(c *Context) error
}

Deleter interface is an interface representing a handler for HTTP DELETE request.

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.

func (*Event) Trigger added in v0.7.0

func (e *Event) Trigger(name string, args ...interface{}) error

Trigger emits the event. The name is an event name that is defined in e.HandlerMap. If args given, they will be passed to event handler that is defined in e.HandlerMap.

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

type Flash map[string]FlashData

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.

func (Flash) Get

func (f Flash) Get(key string) string

Get gets a value associated with the given key. If there is the no value associated with the key, Get returns "".

func (Flash) Len

func (f Flash) Len() int

Len returns a length of the dataset.

func (Flash) Set

func (f Flash) Set(key, value string)

Set sets the value associated with key. It replaces the existing value associated with key.

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 Getter

type Getter interface {
	GET(c *Context) error
}

Getter interface is an interface representing a handler for HTTP GET request.

type Header interface {
	HEAD(c *Context) error
}

Header interface is an interface representing a handler for HTTP HEAD request.

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

func (*Migration) Down

func (mig *Migration) Down(limit int) error

func (*Migration) Up

func (mig *Migration) Up(limit int) error

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

type ParamError struct {
	Name string
	Err  error
}

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

type Params struct {
	url.Values
	// contains filtered or unexported fields
}

Params represents a form values.

func (*Params) Bind

func (params *Params) Bind(obj interface{}, fieldNames ...string) error

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().

func (*Params) From

func (params *Params) From(name string, children ...string) *Params

From returns a new Params that has prefix made from given name and children.

type Patcher

type Patcher interface {
	PATCH(c *Context) error
}

Patcher interface is an interface representing a handler for HTTP PATCH request.

type Poster

type Poster interface {
	POST(c *Context) error
}

Poster interface is an interface representing a handler for HTTP POST request.

type Putter

type Putter interface {
	PUT(c *Context) error
}

Putter interface is an interface representing a handler for HTTP PUT request.

type Request

type Request struct {
	*http.Request
}

Request represents a request.

func (*Request) IsSSL

func (r *Request) IsSSL() bool

IsSSL returns whether the current connection is secure.

func (*Request) IsXHR added in v0.7.0

func (r *Request) IsXHR() bool

IsXHR returns whether the XHR request.

func (*Request) Scheme

func (r *Request) Scheme() string

Scheme returns current scheme of HTTP connection.

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.

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies returns a slice of *http.Cookie.

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the response.

type Route

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

Route represents a route.

func (*Route) ParamNames

func (route *Route) ParamNames() (names []string)

ParamNames returns names of the path parameters.

type RouteTable

type RouteTable []*Route

The routing table.

type Router

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

Router represents a router of kocha.

func (*Router) Reverse

func (router *Router) Reverse(name string, v ...interface{}) (string, error)

Reverse returns path of route by name and any params.

type Session

type Session map[string]string

Session represents a session data store.

func (Session) Clear

func (sess Session) Clear()

Clear clear the all session data.

func (Session) Del

func (sess Session) Del(key string)

Del deletes the value associated with the key.

func (Session) Get

func (sess Session) Get(key string) string

Get gets a value associated with the given key. If there is the no value associated with the given key, Get returns "".

func (Session) Set

func (sess Session) Set(key, value string)

Set sets the value associated with the key. If replaces the existing value associated with the key.

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.

func (*Template) Get

func (t *Template) Get(layout, name, format string) (*template.Template, error)

Get gets a parsed template.

type TemplateFuncMap

type TemplateFuncMap template.FuncMap

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.

type Unit

type Unit interface {
	// ActiveIf returns whether the Unit is active.
	ActiveIf() bool
}

Unit is an interface that Unit for FeatureToggle.

type Validator added in v0.7.0

type Validator interface {
	// Validate validates the middleware.
	// Validate will be called in boot-time of the application.
	Validate() error
}

Validator is the interface to validate the middleware.

Jump to

Keyboard shortcuts

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