macaron

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

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

Go to latest
Published: Oct 20, 2014 License: Apache-2.0 Imports: 29 Imported by: 0

README

Macaron wercker status

Macaron Logo

Package macaron is a high productive and modular design web framework in Go.

Current version: 0.3.0

Getting Started

To install Macaron:

go get github.com/Unknwon/macaron

The very basic usage of Macaron:

package main

import "github.com/Unknwon/macaron"

func main() {
	m := macaron.Classic()
	m.Get("/", func() string {
		return "Hello world!"
	})
	m.Run()
}

Features

  • Powerful routing with suburl.
  • Flexible routes combinations.
  • Unlimited nested group routers.
  • Easy to plugin/unplugin features with modular design.
  • Handy dependency injection powered by inject.
  • Better router layer and less reflection make faster speed.

Use Cases

Getting Help

Credits

License

This project is under Apache v2 License. See the LICENSE file for the full license text.

Documentation

Overview

Package macaron is a high productive and modular design web framework in Go.

Index

Constants

View Source
const (
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLength   = "Content-Length"
	HeaderContentType     = "Content-Type"
	HeaderVary            = "Vary"
)
View Source
const (
	DEV  string = "development"
	PROD string = "production"
	TEST string = "test"
)
View Source
const (
	ContentType   = "Content-Type"
	ContentLength = "Content-Length"
	ContentBinary = "application/octet-stream"
	ContentJSON   = "application/json"
	ContentHTML   = "text/html"
	ContentXHTML  = "application/xhtml+xml"
	ContentXML    = "text/xml"
)

Variables

View Source
var (
	// Env is the environment that Macaron is executing in.
	// The MACARON_ENV is read on initialization to set this variable.
	Env = DEV

	// Path of work directory.
	Root string

	// Flash applies to current request.
	FlashNow bool
)

Functions

func GetDefaultListenAddr

func GetDefaultListenAddr() string

GetDefaultListenAddr returns default server listen address of Macaron.

func NewRouteMap

func NewRouteMap() *routeMap

NewRouteMap initializes and returns a new routeMap.

func Version

func Version() string

Types

type BeforeFunc

type BeforeFunc func(ResponseWriter)

BeforeFunc is a function that is called before the ResponseWriter has been written to.

type ComboRouter

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

ComboRouter represents a combo router.

func (*ComboRouter) Delete

func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter

func (*ComboRouter) Get

func (cr *ComboRouter) Get(h ...Handler) *ComboRouter

func (*ComboRouter) Head

func (cr *ComboRouter) Head(h ...Handler) *ComboRouter

func (*ComboRouter) Options

func (cr *ComboRouter) Options(h ...Handler) *ComboRouter

func (*ComboRouter) Patch

func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter

func (*ComboRouter) Post

func (cr *ComboRouter) Post(h ...Handler) *ComboRouter

func (*ComboRouter) Put

func (cr *ComboRouter) Put(h ...Handler) *ComboRouter

type Context

type Context struct {
	inject.Injector

	*Router
	Req  Request
	Resp ResponseWriter

	Render // Not nil only if you use macaran.Render middleware.
	Locale
	Data map[string]interface{}
	// contains filtered or unexported fields
}

Context represents the runtime context of current request of Macaron instance. It is the integration of most frequently used middlewares and helper methods.

func (*Context) ChangeStaticPath

func (ctx *Context) ChangeStaticPath(oldPath, newPath string)

ChangeStaticPath changes static path from old to new one.

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) string

GetCookie returns given cookie value from request header.

func (*Context) GetFile

func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error)

GetFile returns information about user upload file by given form field name.

func (*Context) GetSecureCookie

func (ctx *Context) GetSecureCookie(key string) (string, bool)

GetSecureCookie returns given cookie value from request header with default secret string.

func (*Context) GetSuperSecureCookie

func (ctx *Context) GetSuperSecureCookie(Secret, key string) (string, bool)

GetSuperSecureCookie returns given cookie value from request header with secret string.

func (*Context) HTML

func (ctx *Context) HTML(status int, name string, binding ...interface{})

HTML calls Render.HTML but allows less arguments.

func (*Context) Next

func (c *Context) Next()

func (*Context) Params

func (ctx *Context) Params(name string) string

Params returns value of given param name.

func (*Context) Query

func (ctx *Context) Query(name string) string

Query querys form parameter.

func (*Context) QueryInt

func (ctx *Context) QueryInt(name string) int

QueryInt returns query result in int type.

func (*Context) QueryInt64

func (ctx *Context) QueryInt64(name string) int64

QueryInt64 returns query result in int64 type.

func (*Context) QueryStrings

func (ctx *Context) QueryStrings(name string) []string

QueryStrings returns a list of results by given query name.

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() string

RemoteAddr returns more real IP address.

func (*Context) ServeFile

func (ctx *Context) ServeFile(file string, names ...string)

ServeFile serves given file to response.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name string, value string, others ...interface{})

SetCookie sets given cookie value to response header.

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(name, value string, others ...interface{})

SetSecureCookie sets given cookie value to response header with default secret string.

func (*Context) SetSuperSecureCookie

func (ctx *Context) SetSuperSecureCookie(Secret, name, value string, others ...interface{})

SetSuperSecureCookie sets given cookie value to response header with secret string.

func (*Context) Written

func (c *Context) Written() bool

type Delims

type Delims struct {
	// Left delimiter, defaults to {{
	Left string
	// Right delimiter, defaults to }}
	Right string
}

Delims represents a set of Left and Right delimiters for HTML template rendering

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
}

HTMLOptions is a struct for overriding some rendering Options for specific HTML call

type Handle

type Handle func(http.ResponseWriter, *http.Request, Params)

Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).

type Handler

type Handler interface{}

Handler can be any callable function. Macaron attempts to inject services into the handler's argument list, and panics if an argument could not be fullfilled via dependency injection.

func Gziper

func Gziper() Handler

Gziper returns a Handler that adds gzip compression to all requests. Make sure to include the Gzip middleware above other middleware that alter the response body (like the render middleware).

func Logger

func Logger() Handler

Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.

func Recovery

func Recovery() Handler

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. While Martini is in development mode, Recovery will also output the panic as HTML.

func Renderer

func Renderer(options ...RenderOptions) Handler

Renderer is a Middleware that maps a macaron.Render service into the Macaron handler chain. An single variadic macaron.RenderOptions struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default file extension is ".tmpl" and ".html".

If MACARON_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the MACARON_ENV environment variable to "production".

func Static

func Static(directory string, staticOpt ...StaticOptions) Handler

Static returns a middleware handler that serves static files in the given directory.

type Locale

type Locale interface {
	Language() string
	Tr(string, ...interface{}) string
}

Locale reprents a localization interface.

type Macaron

type Macaron struct {
	inject.Injector

	*Router
	// contains filtered or unexported fields
}

Macaron represents the top level web application. inject.Injector methods can be invoked to map services on a global level.

func Classic

func Classic() *Macaron

Classic creates a classic Macaron with some basic default middleware: mocaron.Logger, mocaron.Recovery and mocaron.Static.

func New

func New() *Macaron

New creates a bare bones Macaron instance. Use this method if you want to have full control over the middleware that is used.

func NewWithLogger

func NewWithLogger(out io.Writer) *Macaron

NewWithLogger creates a bare bones Macaron instance. Use this method if you want to have full control over the middleware that is used. You can specify logger output writer with this function.

func (*Macaron) Action

func (m *Macaron) Action(handler Handler)

Action sets the handler that will be called after all the middleware has been invoked. This is set to macaron.Router in a macaron.Classic().

func (*Macaron) Handlers

func (m *Macaron) Handlers(handlers ...Handler)

Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers, and panics if any of the handlers is not a callable function

func (*Macaron) Run

func (m *Macaron) Run()

Run the http server. Listening on os.GetEnv("PORT") or 4000 by default.

func (*Macaron) RunOnAddr

func (m *Macaron) RunOnAddr(addr string)

RunOnAddr runs server in given address and port.

func (*Macaron) ServeHTTP

func (m *Macaron) ServeHTTP(resp http.ResponseWriter, req *http.Request)

ServeHTTP is the HTTP Entry point for a Macaron instance. Useful if you want to control your own HTTP server. Be aware that none of middleware will run without registering any router.

func (*Macaron) SetDefaultCookieSecret

func (m *Macaron) SetDefaultCookieSecret(secret string)

SetDefaultCookieSecret sets global default secure cookie secret.

func (*Macaron) SetURLPrefix

func (m *Macaron) SetURLPrefix(prefix string)

SetURLPrefix sets URL prefix of router layer, so that it support suburl.

func (*Macaron) Use

func (m *Macaron) Use(handler Handler)

Use adds a middleware Handler to the stack, and panics if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.

type Params

type Params map[string]string

type Render

type Render interface {
	http.ResponseWriter
	RW() http.ResponseWriter

	JSON(int, interface{})
	JSONString(interface{}) (string, error)
	RawData(int, []byte)
	RenderData(int, []byte)
	HTML(int, string, interface{}, ...HTMLOptions)
	HTMLString(string, interface{}, ...HTMLOptions) (string, error)
	XML(int, interface{})
	Error(int, ...string)
	Status(int)
	Redirect(string, ...int)
	SetTemplatePath(string)
}

type RenderOptions

type RenderOptions struct {
	// Directory to load templates. Default is "templates"
	Directory string
	// Layout template name. Will not render a layout if "". Defaults to "".
	Layout string
	// Extensions to parse template files from. Defaults to [".tmpl", ".html"]
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
	Funcs []template.FuncMap
	// Delims sets the action delimiters to the specified strings in the Delims struct.
	Delims Delims
	// Appends the given charset to the Content-Type header. Default is "UTF-8".
	Charset string
	// Outputs human readable JSON
	IndentJSON bool
	// Outputs human readable XML
	IndentXML bool
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
}

RenderOptions represents a struct for specifying configuration options for the Render middleware.

type Request

type Request struct {
	*http.Request
}

A Request represents an HTTP request received by a server or to be sent by a client.

func (*Request) Body

func (r *Request) Body() *RequestBody

type RequestBody

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

Body is the request's body.

func (*RequestBody) Bytes

func (rb *RequestBody) Bytes() ([]byte, error)

func (*RequestBody) ReadCloser

func (rb *RequestBody) ReadCloser() io.ReadCloser

func (*RequestBody) String

func (rb *RequestBody) String() (string, error)

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(BeforeFunc)
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type ReturnHandler

type ReturnHandler func(*Context, []reflect.Value)

ReturnHandler is a service that Martini provides that is called when a route handler returns something. The ReturnHandler is responsible for writing to the ResponseWriter based on the values that are passed into this function.

type Router

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

Router represents a Macaron router layer.

func NewRouter

func NewRouter() *Router

func (*Router) Any

func (r *Router) Any(pattern string, h ...Handler)

Any is a shortcut for r.Handle("*", pattern, handlers)

func (*Router) Combo

func (r *Router) Combo(pattern string) *ComboRouter

Combo returns a combo router.

func (*Router) Delete

func (r *Router) Delete(pattern string, h ...Handler)

Delete is a shortcut for r.Handle("DELETE", pattern, handlers)

func (*Router) Get

func (r *Router) Get(pattern string, h ...Handler)

Get is a shortcut for r.Handle("GET", pattern, handlers)

func (*Router) Group

func (r *Router) Group(pattern string, fn func(*Router), h ...Handler)

func (*Router) Handle

func (r *Router) Handle(method string, pattern string, handlers []Handler)

Handle registers a new request handle with the given pattern, method and handlers.

func (*Router) Head

func (r *Router) Head(pattern string, h ...Handler)

Head is a shortcut for r.Handle("HEAD", pattern, handlers)

func (*Router) NotFound

func (r *Router) NotFound(handlers ...Handler)

Configurable http.HandlerFunc which is called when no matching route is found. If it is not set, http.NotFound is used. Be sure to set 404 response code in your handler.

func (*Router) Options

func (r *Router) Options(pattern string, h ...Handler)

Options is a shortcut for r.Handle("OPTIONS", pattern, handlers)

func (*Router) Patch

func (r *Router) Patch(pattern string, h ...Handler)

Patch is a shortcut for r.Handle("PATCH", pattern, handlers)

func (*Router) Post

func (r *Router) Post(pattern string, h ...Handler)

Post is a shortcut for r.Handle("POST", pattern, handlers)

func (*Router) Put

func (r *Router) Put(pattern string, h ...Handler)

Put is a shortcut for r.Handle("PUT", pattern, handlers)

func (*Router) Route

func (r *Router) Route(pattern, methods string, h ...Handler)

Route is a shortcut for same handlers but different HTTP methods.

Example:

m.Route("/", "GET,POST", h)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(resp http.ResponseWriter, req *http.Request)

type StaticOptions

type StaticOptions struct {
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// SkipLogging will disable [Static] log messages when a static file is served.
	SkipLogging bool
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string
	// Expires defines which user-defined function to use for producing a HTTP Expires Header
	// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
	Expires func() string
}

StaticOptions is a struct for specifying configuration options for the macaron.Static middleware.

type TplRender

type TplRender struct {
	http.ResponseWriter
	Req *http.Request

	Opt             *RenderOptions
	CompiledCharset string
	// contains filtered or unexported fields
}

func (*TplRender) Error

func (r *TplRender) Error(status int, message ...string)

Error writes the given HTTP status to the current ResponseWriter

func (*TplRender) HTML

func (r *TplRender) HTML(status int, name string, binding interface{}, htmlOpt ...HTMLOptions)

func (*TplRender) HTMLString

func (r *TplRender) HTMLString(name string, binding interface{}, htmlOpt ...HTMLOptions) (string, error)

func (*TplRender) JSON

func (r *TplRender) JSON(status int, v interface{})

func (*TplRender) JSONString

func (r *TplRender) JSONString(v interface{}) (string, error)

func (*TplRender) RW

func (r *TplRender) RW() http.ResponseWriter

func (*TplRender) RawData

func (r *TplRender) RawData(status int, v []byte)

func (*TplRender) Redirect

func (r *TplRender) Redirect(location string, status ...int)

func (*TplRender) RenderData

func (r *TplRender) RenderData(status int, v []byte)

func (*TplRender) SetTemplatePath

func (r *TplRender) SetTemplatePath(newPath string)

SetTemplatePath changes templates path.

func (*TplRender) Status

func (r *TplRender) Status(status int)

func (*TplRender) XML

func (r *TplRender) XML(status int, v interface{})

type Tree

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

Tree represents a router tree for Macaron instance.

func NewTree

func NewTree() *Tree

NewTree initializes and returns a router tree.

func (*Tree) AddRouter

func (t *Tree) AddRouter(pattern string, handle Handle)

AddRouter adds a new route to router tree.

func (*Tree) Match

func (t *Tree) Match(pattern string) (Handle, Params)

Match returns Handle and params if any route is matched.

Directories

Path Synopsis
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.

Jump to

Keyboard shortcuts

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