Macaron 核心概念
下面是 macaron.Classic
已经包含的功能:
- 请求/响应日志 -
- 容错恢复 -
macaron.Recovery
- 静态文件服务 -
任何类型为 macaron.Macaron
的对象都可以被认为是 Macaron 的实例,您可以在单个程序中使用任意数量的 Macaron 实例。
处理器是 Macaron 的灵魂和核心所在. 一个处理器基本上可以是任何的函数:
m.Get("/", func() string {
return "hello world"
})
如果想要将同一个函数作用于多个路由,则可以使用一个命名函数:
m.Get("/", myHandler)
m.Get("/hello", myHandler)
func myHandler() string {
return "hello world"
}
当一个处理器返回结果的时候, Macaron 将会把返回值作为字符串写入到当前的 里面:
m.Get("/", func() string {
return "hello world" // HTTP 200 : "hello world"
m.Get("/", func() *string {
str := "hello world"
return &str // HTTP 200 : "hello world"
})
m.Get("/", func() []byte {
return []byte("hello world") // HTTP 200 : "hello world"
})
m.Get("/", func() error {
// 返回 nil 则什么都不会发生
return nil
}, func() error {
// ... 得到了错误
return err // HTTP 500 : <错误消息>
})
另外你也可以选择性的返回状态码(仅适用于 string
和 []byte
类型):
m.Get("/", func() (int, string) {
return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot"
})
m.Get("/", func() (int, *string) {
return 418, &str // HTTP 418 : "i'm a teapot"
})
m.Get("/", func() (int, []byte) {
})
处理器是通过反射来调用的,Macaron 通过 依赖注入 来为处理器注入参数列表。 这样使得 Macaron 与 Go 语言的 接口完全兼容。
如果你加入一个参数到你的处理器, Macaron 将会搜索它参数列表中的服务,并且通过类型判断来解决依赖关系:
m.Get("/", func(ctx *macaron.Context) {
ctx.Resp.WriteHeader(200) // HTTP 200
})
下面的这些服务已经被包含在经典 Macaron 中(macaron.Classic
):
- - HTTP 请求上下文
*log.Logger
- Macaron 全局日志器- - HTTP 响应流
*http.Request
- HTTP 请求对象
中间件处理器是工作于请求和路由之间的。本质上来说和 Macaron 其他的处理器没有分别. 您可以使用如下方法来添加一个中间件处理器到队列中:
m.Use(func() {
// 处理中间件事务
})
你可以通过 Handlers
函数对中间件队列实现完全的控制. 它将会替换掉之前的任何设置过的处理器:
中间件处理器可以非常好处理一些功能,包括日志记录、授权认证、会话(sessions)处理、错误反馈等其他任何需要在发生在 HTTP 请求之前或者之后的操作:
// 验证一个 API 密钥
m.Use(func(ctx *macaron.Context) {
if ctx.Req.Header.Get("X-API-KEY") != "secret123" {
ctx.Resp.WriteHeader(http.StatusUnauthorized)
}
})