一个 Group 对象需要具备哪些属性呢?首先是前缀(prefix),比如/,或者/api;要支持分组嵌套,那么需要知道当前分组的父亲(parent)是谁;当然了,按照我们一开始的分析,中间件是应用在分组上的,那还需要存储应用在该分组上的中间件(middlewares)。还记得,我们之前调用函数(*Engine).addRoute()来映射所有的路由规则和 Handler 。如果Group对象需要直接映射路由规则的话,比如我们想在使用框架时,这么调用:
RouterGroup struct { prefix string middlewares []HandlerFunc // support middleware parent *RouterGroup // support nesting engine *Engine // all groups share a Engine instance }
// New is the constructor of gee.Engine funcNew() *Engine { engine := &Engine{router: newRouter()} engine.RouterGroup = &RouterGroup{engine: engine} engine.groups = []*RouterGroup{engine.RouterGroup} return engine }
// Group is defined to create a new RouterGroup // remember all groups share the same Engine instance func(group *RouterGroup)Group(prefix string) *RouterGroup { engine := group.engine newGroup := &RouterGroup{ prefix: group.prefix + prefix, parent: group, engine: engine, } engine.groups = append(engine.groups, newGroup) return newGroup }
// GET defines the method to add GET request func(group *RouterGroup)GET(pattern string, handler HandlerFunc) { group.addRoute("GET", pattern, handler) }
// POST defines the method to add POST request func(group *RouterGroup)POST(pattern string, handler HandlerFunc) { group.addRoute("POST", pattern, handler) }