go从0到1项目实战体系四十二:默认路由分析

(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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值