(1). New()对应源码:
// 作用:检查一下Engine有没有实现IRouter这个接口
// 可以及时发现问题,看后面这个结构体有没有实现这个接口
var _ IRouter = &Engine{}
// New returns a new blank Engine instance without any middleware attached.
// By default the configuration is:
// - RedirectTrailingSlash: true
// - RedirectFixedPath: false
// - HandleMethodNotAllowed: false
// - ForwardedByClientIP: true
// - UseRawPath: false
// - UnescapePathValues: true
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
basePath: "/",
root: true,
},
FuncMap: template.FuncMap{},
RedirectTrailingSlash: true,
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
AppEngine: defaultAppEngine,
UseRawPath: false,
RemoveExtraSlash: false,
UnescapePathValues: true,
MaxMultipartMemory: defaultMultipartMemory,
trees: make(methodTrees, 0, 9),
delims: render.Delims{Left: "{{", Right: "}}"},
secureJsonPrefix: "while(1);",
}
engine.RouterGroup.engine = engine
engine.pool.New = func() interface{} {
return engine.allocateContext()
}
return engine
}
(2). Use()对应源码:
// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
// 接收的参数HandlerFunc
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
// 将多个HandlerFunc一个一个传进去
engine.RouterGroup.Use(middleware...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
return engine
}
(3). HandlerFunc源码:
// HandlerFunc defines the handler used by gin middleware as return value.
type HandlerFunc func(*Context)
注:
①. 将函数当成一个类型.
②. 任何返回这个类型的都可以当成中间件.
(4). gin.Default()对应源码:
// Default returns an Engine instance with the Logger and Recovery middleware already attached.
func Default() *Engine {
debugPrintWARNINGDefault()
// 表示创建一个Engine
engine := New() => 也可以直接gin.New(),就表示创建一个不带默认中间件的router
// 这里默认使用了两个中间件,所以,为什么console会有日志输出
// Logger中间件(打印一些日志)、Recovery中间件(返回一个painc错误)
engine.Use(Logger(), Recovery())
return engine
}