gin原始碼
阿新 • • 發佈:2020-12-13
1 gin.Default()如下,裡面包含了New(),
// 這個函式就是生成一個gin框架的基本物件,用於後續傳入net/http進行處理, func Default() *Engine { debugPrintWARNINGDefault() // 也可以直接用New(),相當於省去了兩個中介軟體,一個是日誌輸出,一個是處理異常, engine := New() engine.Use(Logger(), Recovery()) return engine } func New() *Engine { debugPrintWARNINGNew() engine :View Code= &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就是個存放map的陣列,key是http請求的方法名,型別為string,// values是對應生成的字首樹,每個方法生成一個,9是所有不同請求種類的個數, 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 } // 這個是為路由新增中介軟體的函式,傳入的是個可變引數,注意本質上是新增到engine下的RouterGroup中了, func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() }
2