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
  • 全局映射
  • 请求级别的映射
  • 映射值到接口

Was this helpful?

  1. 简体中文

自定义服务

Previous核心服务Next中间件和辅助模块

Last updated 5 years ago

Was this helpful?

服务即是被注入到处理器中的参数. 你可以映射一个服务到 全局 或者 请求 的级别.

全局映射

因为 Macaron 实现了 的接口, 那么映射一个服务就变得非常简单:

db := &MyDatabase{}
m := macaron.Classic()
m.Map(db) // Service will be available to all handlers as *MyDatabase
m.Get("/", func(db *MyDatabase) {
    // Operations with db.
})
m.Run()

请求级别的映射

映射在请求级别的服务可以通过 来完成:

func MyCustomLoggerHandler(ctx *macaron.Context) {
    logger := &MyCustomLogger{ctx.Req}
    ctx.Map(logger) // mapped as *MyCustomLogger
}

func main() {
    //...
    m.Get("/", MyCustomLoggerHandler, func(logger *MyCustomLogger) {
        // Operations with logger.
    })
    m.Get("/panic", func(logger *MyCustomLogger) {
        // This will panic because no logger service maps to this request.
    })
    //...
}

映射值到接口

func WrapResponseWriter(ctx *macaron.Context) {
    rw := NewSpecialResponseWriter(ctx.Resp)
    // override ResponseWriter with our wrapper ResponseWriter
    ctx.MapTo(rw, (*http.ResponseWriter)(nil)) 
}

如此一来,您不仅可以修改自定义的实现而不对客户代码做任何修改,还可以允许对于相同类型的服务使用多种实现。

关于服务最强悍的地方之一就是它能够映射服务到接口. 例如说, 假设你想要覆盖 成为一个对象, 那么你可以封装它并包含你自己的额外操作, 你可以如下这样来编写你的处理器:

inject.Injector
*macaron.Context
http.ResponseWriter