Macaron Documentation
  • Welcome
  • Starter Guide
  • Core Concepts
  • Core Services
  • Custom Services
  • Middlewares
    • Routing
    • Templating
    • Gzip
    • Localization
    • Data Binding and Validation
    • Cache
    • Captcha
    • Session
    • Cross-Site Request Forgery
    • Embed Binary Data
    • Serving Multiple Sites
  • FAQs
  • 简体中文
    • 初学者指南
    • 核心概念
    • 核心服务
    • 自定义服务
    • 中间件和辅助模块
      • 路由模块
      • 模板引擎
      • Gzip 压缩
      • 应用本地化
      • 数据绑定与验证
      • 缓存管理(Cache)
      • 验证码服务
      • 会话管理(Session)
      • 跨域请求攻击(CSRF)
      • 嵌入二进制数据
      • 服务多个站点
    • 常见问题
Powered by GitBook
On this page
  • Context
  • Next()
  • Cookie
  • Other Helper methods
  • Router Logger
  • Panic Recovery
  • Static Files
  • Example
  • Options
  • Multiple Static Handlers
  • Others Services
  • Global Logger
  • Response Stream
  • Request Object

Was this helpful?

Core Services

PreviousCore ConceptsNextCustom Services

Last updated 5 years ago

Was this helpful?

By default, Macaron injects some services to power your application, those services are known as core services, which means you can directly use them as handler arguments without any additional work.

Context

This service is represented by type . This is the very core service for everything you do upon Macaron. It contains all the information you need for request, response, templating, data store, and inject or retrieve other services.

To use it:

package main

import "gopkg.in/macaron.v1"

func Home(ctx *macaron.Context) {
    // ...
}

Next()

Method is an optional feature that Middleware Handlers can call to yield the until after the other Handlers have been executed. This works really well for any operations that must happen after an HTTP request:

// log before and after a request
m.Use(func(ctx *macaron.Context, log *log.Logger){
    log.Println("before a request")

    ctx.Next()

    log.Println("after a request")
})

Cookie

The very basic usage of cookie is just:

To use them:

// ...
m.Get("/set", func(ctx *macaron.Context) {
    ctx.SetCookie("user", "Unknwon", 1)
})

m.Get("/get", func(ctx *macaron.Context) string {
    return ctx.GetCookie("user")
})
// ...

Use following arguments order to set more properties: SetCookie(<name>, <value>, <max age>, <path>, <domain>, <secure>, <http only>,<expires>).

For example, the most advanced usage would be: SetCookie("user", "unknwon", 999, "/", "localhost", true, true, time.Now()).

Note that order is fixed.

These two methods uses default secret string you set globally to encode and decode values.

To use them:

// ...
m.SetDefaultCookieSecret("macaron")
m.Get("/set", func(ctx *macaron.Context) {
    ctx.SetSecureCookie("user", "Unknwon", 1)
})

m.Get("/get", func(ctx *macaron.Context) string {
    name, _ := ctx.GetSecureCookie("user")
    return name
})
// ...

For people who wants even more secure cookies that change secret string every time, just use:

To use them:

// ...
m.Get("/set", func(ctx *macaron.Context) {
    ctx.SetSuperSecureCookie("macaron", "user", "Unknwon", 1)
})

m.Get("/get", func(ctx *macaron.Context) string {
    name, _ := ctx.GetSuperSecureCookie("macaron", "user")
    return name
})
// ...

Other Helper methods

Router Logger

To use it:

package main

import "gopkg.in/macaron.v1"

func main() {
    m := macaron.New()
    m.Use(macaron.Logger())
    // ...
}
[Macaron] Started GET /docs/middlewares/core.html for [::1]
[Macaron] Completed /docs/middlewares/core.html 200 OK in 2.114956ms

Panic Recovery

To use it:

package main

import "gopkg.in/macaron.v1"

func main() {
    m := macaron.New()
    m.Use(macaron.Recovery())
    // ...
}

Static Files

To use it:

package main

import "gopkg.in/macaron.v1"

func main() {
    m := macaron.New()
    m.Use(macaron.Static("public"))
    m.Use(macaron.Static("assets"))
    // ...
}

By default, when you try to request a directory, this service will not list directory files. Instead, it tries to find the index.html file.

[Macaron] Started GET /css/prettify.css for [::1]
[Macaron] [Static] Serving /css/prettify.css
[Macaron] Completed /css/prettify.css 304 Not Modified in 97.584us
[Macaron] Started GET /imgs/macaron.png for [::1]
[Macaron] [Static] Serving /imgs/macaron.png
[Macaron] Completed /imgs/macaron.png 304 Not Modified in 123.211us
[Macaron] Started GET /js/gogsweb.min.js for [::1]
[Macaron] [Static] Serving /js/gogsweb.min.js
[Macaron] Completed /js/gogsweb.min.js 304 Not Modified in 47.653us
[Macaron] Started GET /css/main.css for [::1]
[Macaron] [Static] Serving /css/main.css
[Macaron] Completed /css/main.css 304 Not Modified in 42.58us

Example

Suppose you have following directory structure:

public/
    |__ html
            |__ index.html
    |__ css/
            |__ main.css

Results:

Request URL

Match File

/html/main.html

None

/html/

index.html

/css/main.css

main.css

Options

package main

import "gopkg.in/macaron.v1"

func main() {
    m := macaron.New()
    m.Use(macaron.Static("public",
        macaron.StaticOptions{
            // Prefix is the optional prefix used to serve the static directory content. Default is empty string.
            Prefix: "public",
            // SkipLogging will disable [Static] log messages when a static file is served. Default is false.
            SkipLogging: true,
            // IndexFile defines which file to serve as index if it exists. Default is "index.html".
            IndexFile: "index.html",
            // Expires defines which user-defined function to use for producing a HTTP Expires Header. Default is nil.
            // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
            Expires: func() string { 
                return time.Now().Add(24 * 60 * time.Minute).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
            },
        }))
    // ...
}

Multiple Static Handlers

To use it:

// ...
m.Use(macaron.Statics(macaron.StaticOptions{}, "public", "views"))
// ...

This will register both public and views as static directories.

Others Services

Global Logger

To use it:

package main

import (
    "log"

    "gopkg.in/macaron.v1"
)

func main() {
    m := macaron.Classic()
    m.Get("/", myHandler)
    m.Run()
}

func myHandler(ctx *macaron.Context, logger *log.Logger) string {
    logger.Println("the request path is: " + ctx.Req.RequestURI)
    return "the request path is: " + ctx.Req.RequestURI
}

Response Stream

To use it:

package main

import (
    "gopkg.in/macaron.v1"
)

func main() {
    m := macaron.Classic()
    m.Get("/", myHandler)
    m.Run()
}

func myHandler(ctx *macaron.Context) {
    ctx.Resp.Write([]byte("the request path is: " + ctx.Req.RequestURI))
}

Request Object

Besides, this service provides three methods to help you easily retrieve request body:

To use them:

package main

import (
    "gopkg.in/macaron.v1"
)

func main() {
    m := macaron.Classic()
    m.Get("/body1", func(ctx *macaron.Context) {
        reader, err := ctx.Req.Body().ReadCloser()
        // ...
    })
    m.Get("/body2", func(ctx *macaron.Context) {
        data, err := ctx.Req.Body().Bytes()
        // ...
    })
    m.Get("/body3", func(ctx *macaron.Context) {
        data, err := ctx.Req.Body().String()
        // ...
    })
    m.Run()
}

Notice that request body can only be read once.

, , ,

There are also more secure cookie support. First, you need to call , then use it by calling:

To set/get URL parameters: / , , , ,

To get query parameters: , , , , , ,

To serve content or file: , ,

To get remote IP address:

This service can be injected by function . It is responsible for your application routing log.

This service is injected automatically when you use .

Sample output take from :

This service can be injected by function . It is responsible for recovering your application when panic happens.

This service is injected automatically when you use .

This service can be injected by function . It is responsible for serving static resources of your application, it can be injected as many times as you want if you have multiple static directories.

This service is injected automatically with directory public when you use .

Sample output take from :

This service also accepts second argument for custom options():

In case you have multiple static directories, there is one helper function to make your life easier.

This service is represented by type . It is optional to use, but for convenience when you do not have a global level logger.

This service is injected automatically for every Macaron .

This service is represented by type . It is optional to use, normally, you should use *macaron.Context.Resp.

This service is injected automatically for every Macaron .

This service is represented by type . It is optional to use, normally, you should use *macaron.Context.Req.

: get request body in string type

: get request body in []byte type

: get request body in io.ReadCloser type

Sometimes you need to pass type as an argument, you should use *macaron.Context.Req.Request.

This service is injected automatically for every Macaron .

*macaron.Context
Context.Next
*macaron.Context.SetCookie
*macaron.Context.GetCookie
*macaron.Context.GetCookieInt
*macaron.Context.GetCookieInt64
*macaron.Context.GetCookieFloat64
macaron.SetDefaultCookieSecret
*macaron.Context.SetSecureCookie
*macaron.Context.GetSecureCookie
*macaron.Context.SetSuperSecureCookie
*macaron.Context.GetSuperSecureCookie
ctx.SetParams
ctx.Params
ctx.ParamsEscape
ctx.ParamsInt
ctx.ParamsInt64
ctx.ParamsFloat64
ctx.Query
ctx.QueryEscape
ctx.QueryInt
ctx.QueryInt64
ctx.QueryFloat64
ctx.QueryStrings
ctx.QueryTrim
ctx.ServeContent
ctx.ServeFile
ctx.ServeFileContent
ctx.RemoteAddr
macaron.Logger
macaron.Classic
Peach Docs
macaron.Recovery
macaron.Classic
macaron.Static
macaron.Classic
Peach Docs
macaron.StaticOptions
macaron.Statics
*log.Logger
http.ResponseWriter
*http.Request
*macaron.Context.Req.Body().String()
*macaron.Context.Req.Body().Bytes()
*macaron.Context.Req.Body().ReadCloser()
*http.Request
Instance
Instance
Instance