继上一篇关于inject注入的笔记,理解了martini的关键核心之一:依赖注入。注入回调函数,由运行时进行主动调用执行。这一篇主要是注解martini的骨架martini.go的实现,下面先从一个简单的martini使用实例,即创建一个最简单的http服务器开始。
//martini使用简单实例
package main
import "github.com/go-martini/martini"
func main() {
m := martini.Classic() //获取一个martini实例
m.Get("/", func() string { // 用户自定义路由规则
return "Hello world!"
})
m.Run() // 运行服务器
}
package martini
import (
"log"
"net/http"
"os"
"reflect"
"github.com/codegangsta/inject"
)
// Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level.
type Martini struct {
inject.Injector // 注入工具,利用反射实现函数回调
handlers []Handler // 存储处理http请求的所有中间件
action Handler // 路由匹配以及路由处理,在所有中间件都处理完之后执行
logger *log.Logger // 日志工具
}
// 基础骨架:具备基本的注入与反射调用功能
// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
func New() *Martini {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
}
// Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers.
// Will panic if any of the handlers is not a callable function
// 设置所有的中间件
func (m *Martini) Handlers(handlers ...Handler) {
m.handlers = make([]Handler, 0)
for _, handler := range handlers {
m.Use(handler)
}
}
// Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic().
// 设置真正的路由处理器,所有中间件执行完之后才会执行
func (m *Martini) Action(handler Handler) {
validateHandler(handler)
m.action = handler
}
// Logger sets the logger
func (m *Martini) Logger(logger *log.Logger) {
m.logger = logger
m.Map(m.logger)
}
// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.
// 添加一个中间件处理器,每一个http请求都会先执行, 按照添加的顺序依次执行
func (m *Martini) Use(handler Handler) {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
}
// http接口,每一次http请求 用户级别处理的入口
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {
println("call....")
m.createContext(res, req).run() // 每一个请求创建一个上下文,保存一些必要的信息,之后开始处理请求
}
// Run the http server on a given host and port.
// http 服务器启动
func (m *Martini) RunOnAddr(addr string) {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are passed.
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
logger.Fatalln(http.ListenAndServe(addr, m)) // m是整个框架控制的开始
}
// Run the http server. Listening on os.GetEnv("PORT") or 3000 by default.