improve ghttp.RouterGroup

This commit is contained in:
John 2019-08-10 14:10:47 +08:00
parent 573179060e
commit 846c6a579e
2 changed files with 25 additions and 26 deletions

View File

@ -55,7 +55,7 @@ func (s *Server) handlePreBindItems() {
}
// 获取分组路由对象
func (s *Server) Group(prefix string, groups ...*RouterGroup) *RouterGroup {
func (s *Server) Group(prefix string, groups ...func(g *RouterGroup)) *RouterGroup {
if prefix == "/" {
prefix = ""
}
@ -65,14 +65,14 @@ func (s *Server) Group(prefix string, groups ...*RouterGroup) *RouterGroup {
}
if len(groups) > 0 {
for _, v := range groups {
v.parent = group
v(group)
}
}
return group
}
// 获取分组路由对象(绑定域名)
func (d *Domain) Group(prefix string, groups ...*RouterGroup) *RouterGroup {
func (d *Domain) Group(prefix string, groups ...func(g *RouterGroup)) *RouterGroup {
if prefix == "/" {
prefix = ""
}
@ -82,14 +82,14 @@ func (d *Domain) Group(prefix string, groups ...*RouterGroup) *RouterGroup {
}
if len(groups) > 0 {
for _, v := range groups {
v.parent = group
v(group)
}
}
return group
}
// 层级递归创建分组路由注册项
func (g *RouterGroup) Group(prefix string, groups ...*RouterGroup) *RouterGroup {
func (g *RouterGroup) Group(prefix string, groups ...func(g *RouterGroup)) *RouterGroup {
if prefix == "/" {
prefix = ""
}
@ -97,11 +97,11 @@ func (g *RouterGroup) Group(prefix string, groups ...*RouterGroup) *RouterGroup
parent: g,
server: g.server,
domain: g.domain,
prefix: g.prefix + prefix,
prefix: prefix,
}
if len(groups) > 0 {
for _, v := range groups {
v.parent = group
v(group)
}
}
return group

View File

@ -19,46 +19,45 @@ import (
func Test_Router_Group_Group(t *testing.T) {
p := ports.PopRand()
s := g.Server(p)
g := s.Group("/")
g.Group("/api.v2",
s.Group("/api.v2", func(g *ghttp.RouterGroup) {
g.Middleware(func(r *ghttp.Request) {
r.Response.Write("1")
r.Middleware.Next()
r.Response.Write("2")
}),
})
g.GET("/test", func(r *ghttp.Request) {
r.Response.Write("test")
}),
g.Group("/order",
})
g.Group("/order", func(g *ghttp.RouterGroup) {
g.GET("/list", func(r *ghttp.Request) {
r.Response.Write("list")
}),
})
g.PUT("/update", func(r *ghttp.Request) {
r.Response.Write("update")
}),
),
g.Group("/user",
})
})
g.Group("/user", func(g *ghttp.RouterGroup) {
g.GET("/info", func(r *ghttp.Request) {
r.Response.Write("info")
}),
})
g.POST("/edit", func(r *ghttp.Request) {
r.Response.Write("edit")
}),
})
g.DELETE("/drop", func(r *ghttp.Request) {
r.Response.Write("drop")
}),
),
g.Group("/hook",
})
})
g.Group("/hook", func(g *ghttp.RouterGroup) {
g.Hook("/*", ghttp.HOOK_BEFORE_SERVE, func(r *ghttp.Request) {
r.Response.Write("hook any")
}),
})
g.Hook("/:name", ghttp.HOOK_BEFORE_SERVE, func(r *ghttp.Request) {
r.Response.Write("hook name")
}),
),
)
})
})
})
s.SetPort(p)
//s.SetDumpRouteMap(false)
s.SetDumpRouteMap(false)
s.Start()
defer s.Shutdown()