自定义服务
全局映射
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.
})
//...
}映射值到接口
Last updated
Was this helpful?