macaron

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2025 License: Apache-2.0 Imports: 30 Imported by: 3,661

README ΒΆ

Macaron

GitHub Workflow Status codecov GoDoc Sourcegraph

Macaron Logo

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

πŸ“£ Announcement

  • If you're considering using Macaron, you may want to take a look at Flamego first, which is the successor of the Macaron.
  • That means Macaron is officially in the maintenance mode, and no major features will be added to Macaron.

Getting Started

The minimum requirement of Go is 1.18.

To install Macaron:

go get gopkg.in/macaron.v1

The very basic usage of Macaron:

package main

import "gopkg.in/macaron.v1"

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.
  • Directly integrate with existing services.
  • Dynamically change template files at runtime.
  • Allow to use in-memory template and static files.
  • Easy to plugin/unplugin features with modular design.
  • Handy dependency injection powered by inject.
  • Better router layer and less reflection make faster speed.

Middlewares

Middlewares allow you easily plugin/unplugin features for your Macaron applications.

There are already many middlewares to simplify your work:

  • render - Go template engine
  • static - Serves static files
  • gzip - Gzip compression to all responses
  • binding - Request data binding and validation
  • i18n - Internationalization and Localization
  • cache - Cache manager
  • session - Session manager
  • csrf - Generates and validates csrf tokens
  • captcha - Captcha service
  • pongo2 - Pongo2 template engine support
  • sockets - WebSockets channels binding
  • bindata - Embed binary data as static and template files
  • toolbox - Health check, pprof, profile and statistic services
  • oauth2 - OAuth 2.0 backend
  • authz - ACL/RBAC/ABAC authorization based on Casbin
  • switcher - Multiple-site support
  • method - HTTP method override
  • permissions2 - Cookies, users and permissions
  • renders - Beego-like render engine(Macaron has built-in template engine, this is another option)
  • piwik - Server-side piwik analytics

Use Cases

  • Gogs: A painless self-hosted Git Service
  • Grafana: The open platform for beautiful analytics and monitoring
  • Peach: A modern web documentation server
  • Go Walker: Go online API documentation
  • Critical Stack Intel: A 100% free intel marketplace from Critical Stack, Inc.

Getting Help

Credits

License

This project is under the Apache License, Version 2.0. See the LICENSE file for the full license text.

Documentation ΒΆ

Overview ΒΆ

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

Index ΒΆ

Constants ΒΆ

View Source
const (
	DEV  = "development"
	PROD = "production"
	TEST = "test"
)
View Source
const (
	DEFAULT_TPL_SET_NAME = "DEFAULT"
)

Variables ΒΆ

View Source
var (
	ColorLog      = true
	LogTimeFormat = "2006-01-02 15:04:05"
)
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
)
View Source
var MaxMemory = int64(1024 * 1024 * 10)

MaxMemory is the maximum amount of memory to use when parsing a multipart form. Set this to whatever value you prefer; default is 10 MB.

Functions ΒΆ

func Config ΒΆ

func Config() *ini.File

Config returns configuration convention object. It returns an empty object if there is no one available.

func GenerateETag ΒΆ added in v1.1.12

func GenerateETag(fileSize, fileName, modTime string) string

GenerateETag generates an ETag based on size, filename and file modification time

func GetDefaultListenInfo ΒΆ

func GetDefaultListenInfo() (string, int)

func GetExt ΒΆ

func GetExt(s string) string

func MatchTest ΒΆ added in v1.1.8

func MatchTest(pattern, url string) bool

MatchTest returns true if given URL is matched by given pattern.

func NewRouteMap ΒΆ added in v1.1.8

func NewRouteMap() *routeMap

NewRouteMap initializes and returns a new routeMap.

func ParseTplSet ΒΆ

func ParseTplSet(tplSet string) (tplName string, tplDir string)

func PrepareCharset ΒΆ

func PrepareCharset(charset string) string

func SetConfig ΒΆ

func SetConfig(source interface{}, others ...interface{}) (_ *ini.File, err error)

SetConfig sets data sources for configuration.

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 BeforeHandler ΒΆ

type BeforeHandler func(rw http.ResponseWriter, req *http.Request) bool

BeforeHandler represents a handler executes at beginning of every request. Macaron stops future process when it returns true.

type ComboRouter ΒΆ added in v1.1.8

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

ComboRouter represents a combo router.

func (*ComboRouter) Delete ΒΆ added in v1.1.8

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

func (*ComboRouter) Get ΒΆ added in v1.1.8

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

func (*ComboRouter) Head ΒΆ added in v1.1.8

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

func (*ComboRouter) Name ΒΆ added in v1.1.8

func (cr *ComboRouter) Name(name string)

Name sets name of ComboRouter route.

func (*ComboRouter) Options ΒΆ added in v1.1.8

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

func (*ComboRouter) Patch ΒΆ added in v1.1.8

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

func (*ComboRouter) Post ΒΆ added in v1.1.8

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

func (*ComboRouter) Put ΒΆ added in v1.1.8

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

type Context ΒΆ

type Context struct {
	inject.Injector

	*Router
	Req  Request
	Resp ResponseWriter

	Render
	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) AllParams ΒΆ added in v1.3.5

func (ctx *Context) AllParams() Params

AllParams returns all params.

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) GetCookieFloat64 ΒΆ

func (ctx *Context) GetCookieFloat64(name string) float64

GetCookieFloat64 returns cookie result in float64 type.

func (*Context) GetCookieInt ΒΆ

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

GetCookieInt returns cookie result in int type.

func (*Context) GetCookieInt64 ΒΆ

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

GetCookieInt64 returns cookie result in int64 type.

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, name 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, data ...interface{})

HTML renders the HTML with default template set.

func (*Context) HTMLSet ΒΆ

func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{})

HTMLSet renders the HTML with given template set name.

func (*Context) Next ΒΆ

func (ctx *Context) Next()

Next runs the next handler in the context chain

func (*Context) Params ΒΆ

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

Params returns value of given param name. e.g. ctx.Params(":uid") or ctx.Params("uid")

func (*Context) ParamsEscape ΒΆ

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

ParamsEscape returns escapred params result. e.g. ctx.ParamsEscape(":uname")

func (*Context) ParamsFloat64 ΒΆ

func (ctx *Context) ParamsFloat64(name string) float64

ParamsFloat64 returns params result in int64 type. e.g. ctx.ParamsFloat64(":uid")

func (*Context) ParamsInt ΒΆ

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

ParamsInt returns params result in int type. e.g. ctx.ParamsInt(":uid")

func (*Context) ParamsInt64 ΒΆ

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

ParamsInt64 returns params result in int64 type. e.g. ctx.ParamsInt64(":uid")

func (*Context) Query ΒΆ

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

Query querys form parameter.

func (*Context) QueryBool ΒΆ added in v1.1.7

func (ctx *Context) QueryBool(name string) bool

QueryBool returns query result in bool type.

func (*Context) QueryEscape ΒΆ

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

QueryEscape returns escapred query result.

func (*Context) QueryFloat64 ΒΆ

func (ctx *Context) QueryFloat64(name string) float64

QueryFloat64 returns query result in float64 type.

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) QueryTrim ΒΆ

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

QueryTrim querys and trims spaces form parameter.

func (*Context) Redirect ΒΆ

func (ctx *Context) Redirect(location string, status ...int)

Redirect sends a redirect response

func (*Context) RemoteAddr ΒΆ

func (ctx *Context) RemoteAddr() string

RemoteAddr returns more real IP address.

func (*Context) ReplaceAllParams ΒΆ added in v1.2.2

func (ctx *Context) ReplaceAllParams(params Params)

ReplaceAllParams replace all current params with given params

func (*Context) SaveToFile ΒΆ

func (ctx *Context) SaveToFile(name, savePath string) error

SaveToFile reads a file from request by field name and saves to given path.

func (*Context) ServeContent ΒΆ

func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{})

ServeContent serves given content to response.

func (*Context) ServeFile ΒΆ

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

ServeFile serves given file to response.

func (*Context) ServeFileContent ΒΆ

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

ServeFileContent serves given file as content to response.

func (*Context) SetCookie ΒΆ

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

SetCookie sets given cookie value to response header. FIXME: IE support? http://golanghome.com/post/620#reply2

func (*Context) SetParams ΒΆ

func (ctx *Context) SetParams(name, val string)

SetParams sets value of param with given name.

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 (ctx *Context) Written() bool

Written returns whether the context response has been written to

type ContextInvoker ΒΆ added in v1.2.0

type ContextInvoker func(ctx *Context)

ContextInvoker is an inject.FastInvoker wrapper of func(ctx *Context).

func (ContextInvoker) Invoke ΒΆ added in v1.2.0

func (invoke ContextInvoker) Invoke(params []interface{}) ([]reflect.Value, error)

Invoke implements inject.FastInvoker which simplifies calls of `func(ctx *Context)` function.

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 DummyRender ΒΆ

type DummyRender struct {
	http.ResponseWriter
}

DummyRender is used when user does not choose any real render to use. This way, we can print out friendly message which asks them to register one, instead of ugly and confusing 'nil pointer' panic.

func (*DummyRender) Error ΒΆ

func (r *DummyRender) Error(int, ...string)

func (*DummyRender) HTML ΒΆ

func (r *DummyRender) HTML(int, string, interface{}, ...HTMLOptions)

func (*DummyRender) HTMLBytes ΒΆ

func (r *DummyRender) HTMLBytes(string, interface{}, ...HTMLOptions) ([]byte, error)

func (*DummyRender) HTMLSet ΒΆ

func (r *DummyRender) HTMLSet(int, string, string, interface{}, ...HTMLOptions)

func (*DummyRender) HTMLSetBytes ΒΆ

func (r *DummyRender) HTMLSetBytes(string, string, interface{}, ...HTMLOptions) ([]byte, error)

func (*DummyRender) HTMLSetString ΒΆ

func (r *DummyRender) HTMLSetString(string, string, interface{}, ...HTMLOptions) (string, error)

func (*DummyRender) HTMLString ΒΆ

func (r *DummyRender) HTMLString(string, interface{}, ...HTMLOptions) (string, error)

func (*DummyRender) HasTemplateSet ΒΆ

func (r *DummyRender) HasTemplateSet(string) bool

func (*DummyRender) JSON ΒΆ

func (r *DummyRender) JSON(int, interface{})

func (*DummyRender) JSONString ΒΆ

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

func (*DummyRender) PlainText ΒΆ

func (r *DummyRender) PlainText(int, []byte)

func (*DummyRender) RawData ΒΆ

func (r *DummyRender) RawData(int, []byte)

func (*DummyRender) SetResponseWriter ΒΆ

func (r *DummyRender) SetResponseWriter(http.ResponseWriter)

func (*DummyRender) SetTemplatePath ΒΆ

func (r *DummyRender) SetTemplatePath(string, string)

func (*DummyRender) Status ΒΆ

func (r *DummyRender) Status(int)

func (*DummyRender) XML ΒΆ

func (r *DummyRender) XML(int, interface{})

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 ΒΆ added in v1.1.8

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 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 Renderers ΒΆ

func Renderers(options RenderOptions, tplSets ...string) Handler

func Static ΒΆ

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

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

func Statics ΒΆ

func Statics(opt StaticOptions, dirs ...string) Handler

Statics registers multiple static middleware handlers all at once.

type Leaf ΒΆ added in v1.1.8

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

Leaf represents a leaf route information.

func NewLeaf ΒΆ added in v1.1.8

func NewLeaf(parent *Tree, pattern string, handle Handle) *Leaf

func (*Leaf) URLPath ΒΆ added in v1.1.8

func (l *Leaf) URLPath(pairs ...string) string

URLPath build path part of URL by given pair values.

type Locale ΒΆ

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

Locale reprents a localization interface.

type LoggerInvoker ΒΆ added in v1.2.0

type LoggerInvoker func(ctx *Context, log *log.Logger)

LoggerInvoker is an inject.FastInvoker wrapper of func(ctx *Context, log *log.Logger).

func (LoggerInvoker) Invoke ΒΆ added in v1.2.0

func (invoke LoggerInvoker) Invoke(params []interface{}) ([]reflect.Value, error)

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: macaron.Logger, macaron.Recovery and macaron.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) Before ΒΆ

func (m *Macaron) Before(handler BeforeHandler)

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(args ...interface{})

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

func (*Macaron) ServeHTTP ΒΆ

func (m *Macaron) ServeHTTP(rw 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 ΒΆ added in v1.1.8

type Params map[string]string

type Render ΒΆ

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

	JSON(int, interface{})
	JSONString(interface{}) (string, error)
	RawData(int, []byte)   // Serve content as binary
	PlainText(int, []byte) // Serve content as plain text
	HTML(int, string, interface{}, ...HTMLOptions)
	HTMLSet(int, string, string, interface{}, ...HTMLOptions)
	HTMLSetString(string, string, interface{}, ...HTMLOptions) (string, error)
	HTMLString(string, interface{}, ...HTMLOptions) (string, error)
	HTMLSetBytes(string, string, interface{}, ...HTMLOptions) ([]byte, error)
	HTMLBytes(string, interface{}, ...HTMLOptions) ([]byte, error)
	XML(int, interface{})
	Error(int, ...string)
	Status(int)
	SetTemplatePath(string, string)
	HasTemplateSet(string) bool
}

type RenderOptions ΒΆ

type RenderOptions struct {
	// Directory to load templates. Default is "templates".
	Directory string
	// Addtional directories to overwite templates.
	AppendDirectories []string
	// Layout template name. Will not render a layout if "". Default is to "".
	Layout string
	// Extensions to parse template files from. Defaults are [".tmpl", ".html"].
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Default is [].
	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
	// TemplateFileSystem is the interface for supporting any implmentation of template file system.
	TemplateFileSystem
}

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

type Request ΒΆ

type Request struct {
	*http.Request
}

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

func (*Request) Body ΒΆ

func (r *Request) Body() *RequestBody

Body returns a RequestBody for the request

type RequestBody ΒΆ

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

RequestBody represents a request body.

func (*RequestBody) Bytes ΒΆ

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

Bytes reads and returns content of request body in bytes.

func (*RequestBody) ReadCloser ΒΆ

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

ReadCloser returns a ReadCloser for request body.

func (*RequestBody) String ΒΆ

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

String reads and returns content of request body in string.

type ResponseWriter ΒΆ

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Pusher
	// 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(method string, 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 Route ΒΆ added in v1.1.8

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

Route represents a wrapper of leaf route and upper level router.

func (*Route) Name ΒΆ added in v1.1.8

func (r *Route) Name(name string)

Name sets name of route.

type Router ΒΆ added in v1.1.8

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

Router represents a Macaron router layer.

func NewRouter ΒΆ added in v1.1.8

func NewRouter() *Router

func (*Router) Any ΒΆ added in v1.1.8

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

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

func (*Router) Combo ΒΆ added in v1.1.8

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

Combo returns a combo router.

func (*Router) Delete ΒΆ added in v1.1.8

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

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

func (*Router) Get ΒΆ added in v1.1.8

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

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

func (*Router) Group ΒΆ added in v1.1.8

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

func (*Router) Handle ΒΆ added in v1.1.8

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

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

func (*Router) Head ΒΆ added in v1.1.8

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

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

func (*Router) InternalServerError ΒΆ added in v1.1.8

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

InternalServerError configurates handler which is called when route handler returns error. If it is not set, default handler is used. Be sure to set 500 response code in your handler.

func (*Router) NotFound ΒΆ added in v1.1.8

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

NotFound configurates 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 ΒΆ added in v1.1.8

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

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

func (*Router) Patch ΒΆ added in v1.1.8

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

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

func (*Router) Post ΒΆ added in v1.1.8

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

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

func (*Router) Put ΒΆ added in v1.1.8

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

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

func (*Router) Route ΒΆ added in v1.1.8

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

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

Example:

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

func (*Router) ServeHTTP ΒΆ added in v1.1.8

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

func (*Router) SetAutoHead ΒΆ added in v1.1.8

func (r *Router) SetAutoHead(v bool)

SetAutoHead sets the value who determines whether add HEAD method automatically when GET method is added.

func (*Router) SetHandlerWrapper ΒΆ added in v1.2.0

func (r *Router) SetHandlerWrapper(f func(Handler) Handler)

SetHandlerWrapper sets handlerWrapper for the router.

func (*Router) URLFor ΒΆ added in v1.1.8

func (r *Router) URLFor(name string, pairs ...string) string

URLFor builds path part of URL by given pair values.

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
	// ETag defines if we should add an ETag header
	// https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#validating-cached-responses-with-etags
	ETag bool
	// FileSystem is the interface for supporting any implmentation of file system.
	FileSystem http.FileSystem
}

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

type TemplateFile ΒΆ

type TemplateFile interface {
	Name() string
	Data() []byte
	Ext() string
}

TemplateFile represents a interface of template file that has name and can be read.

type TemplateFileSystem ΒΆ

type TemplateFileSystem interface {
	ListFiles() []TemplateFile
	Get(string) (io.Reader, error)
}

TemplateFileSystem represents a interface of template file system that able to list all files.

type TemplateSet ΒΆ added in v1.1.5

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

TemplateSet represents a template set of type *template.Template.

func NewTemplateSet ΒΆ added in v1.1.5

func NewTemplateSet() *TemplateSet

NewTemplateSet initializes a new empty template set.

func (*TemplateSet) Get ΒΆ added in v1.1.5

func (ts *TemplateSet) Get(name string) *template.Template

func (*TemplateSet) GetDir ΒΆ added in v1.1.5

func (ts *TemplateSet) GetDir(name string) string

func (*TemplateSet) Set ΒΆ added in v1.1.5

func (ts *TemplateSet) Set(name string, opt *RenderOptions) *template.Template

type TplFile ΒΆ

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

TplFile implements TemplateFile interface.

func NewTplFile ΒΆ

func NewTplFile(name string, data []byte, ext string) *TplFile

NewTplFile cerates new template file with given name and data.

func (*TplFile) Data ΒΆ

func (f *TplFile) Data() []byte

func (*TplFile) Ext ΒΆ

func (f *TplFile) Ext() string

func (*TplFile) Name ΒΆ

func (f *TplFile) Name() string

type TplFileSystem ΒΆ

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

TplFileSystem implements TemplateFileSystem interface.

func NewTemplateFileSystem ΒΆ

func NewTemplateFileSystem(opt RenderOptions, omitData bool) TplFileSystem

NewTemplateFileSystem creates new template file system with given options.

func (TplFileSystem) Get ΒΆ added in v1.1.10

func (fs TplFileSystem) Get(name string) (io.Reader, error)

func (TplFileSystem) ListFiles ΒΆ

func (fs TplFileSystem) ListFiles() []TemplateFile

type TplRender ΒΆ

type TplRender struct {
	http.ResponseWriter
	*TemplateSet
	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, data interface{}, htmlOpt ...HTMLOptions)

func (*TplRender) HTMLBytes ΒΆ

func (r *TplRender) HTMLBytes(name string, data interface{}, htmlOpt ...HTMLOptions) ([]byte, error)

func (*TplRender) HTMLSet ΒΆ

func (r *TplRender) HTMLSet(status int, setName, tplName string, data interface{}, htmlOpt ...HTMLOptions)

func (*TplRender) HTMLSetBytes ΒΆ

func (r *TplRender) HTMLSetBytes(setName, tplName string, data interface{}, htmlOpt ...HTMLOptions) ([]byte, error)

func (*TplRender) HTMLSetString ΒΆ

func (r *TplRender) HTMLSetString(setName, tplName string, data interface{}, htmlOpt ...HTMLOptions) (string, error)

func (*TplRender) HTMLString ΒΆ

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

func (*TplRender) HasTemplateSet ΒΆ

func (r *TplRender) HasTemplateSet(name string) bool

func (*TplRender) JSON ΒΆ

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

func (*TplRender) JSONString ΒΆ

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

func (*TplRender) PlainText ΒΆ

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

func (*TplRender) RawData ΒΆ

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

func (*TplRender) SetResponseWriter ΒΆ

func (r *TplRender) SetResponseWriter(rw http.ResponseWriter)

func (*TplRender) SetTemplatePath ΒΆ

func (r *TplRender) SetTemplatePath(setName, dir string)

func (*TplRender) Status ΒΆ

func (r *TplRender) Status(status int)

func (*TplRender) XML ΒΆ

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

type Tree ΒΆ added in v1.1.8

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

Tree represents a router tree in Macaron.

func NewSubtree ΒΆ added in v1.1.8

func NewSubtree(parent *Tree, pattern string) *Tree

func NewTree ΒΆ added in v1.1.8

func NewTree() *Tree

func (*Tree) Add ΒΆ added in v1.1.8

func (t *Tree) Add(pattern string, handle Handle) *Leaf

func (*Tree) Match ΒΆ added in v1.1.8

func (t *Tree) Match(url string) (Handle, Params, bool)

Directories ΒΆ

Path Synopsis
Package cookie contains helper functions for setting cookie values.
Package cookie contains helper functions for setting cookie values.