服务即是被注入到处理器中的参数. 你可以映射一个服务到 全局 或者 请求 的级别.
Copy 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()
Copy 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.
})
//...
}
Copy func WrapResponseWriter(ctx *macaron.Context) {
rw := NewSpecialResponseWriter(ctx.Resp)
// override ResponseWriter with our wrapper ResponseWriter
ctx.MapTo(rw, (*http.ResponseWriter)(nil))
}