github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_z_unit_feature_router_group_group_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp_test 8 9 import ( 10 "fmt" 11 "testing" 12 "time" 13 14 "github.com/gogf/gf/v2/frame/g" 15 "github.com/gogf/gf/v2/net/ghttp" 16 "github.com/gogf/gf/v2/test/gtest" 17 "github.com/gogf/gf/v2/util/guid" 18 ) 19 20 func Test_Router_Group_Group(t *testing.T) { 21 s := g.Server(guid.S()) 22 s.Group("/api.v2", func(group *ghttp.RouterGroup) { 23 group.Middleware(func(r *ghttp.Request) { 24 r.Response.Write("1") 25 r.Middleware.Next() 26 r.Response.Write("2") 27 }) 28 group.GET("/test", func(r *ghttp.Request) { 29 r.Response.Write("test") 30 }) 31 group.Group("/order", func(group *ghttp.RouterGroup) { 32 group.GET("/list", func(r *ghttp.Request) { 33 r.Response.Write("list") 34 }) 35 group.PUT("/update", func(r *ghttp.Request) { 36 r.Response.Write("update") 37 }) 38 }) 39 group.Group("/user", func(group *ghttp.RouterGroup) { 40 group.GET("/info", func(r *ghttp.Request) { 41 r.Response.Write("info") 42 }) 43 group.POST("/edit", func(r *ghttp.Request) { 44 r.Response.Write("edit") 45 }) 46 group.DELETE("/drop", func(r *ghttp.Request) { 47 r.Response.Write("drop") 48 }) 49 }) 50 group.Group("/hook", func(group *ghttp.RouterGroup) { 51 group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) { 52 r.Response.Write("hook any") 53 }) 54 group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) { 55 r.Response.Write("hook name") 56 }) 57 }) 58 }) 59 s.SetDumpRouterMap(false) 60 s.Start() 61 defer s.Shutdown() 62 63 time.Sleep(100 * time.Millisecond) 64 gtest.C(t, func(t *gtest.T) { 65 client := g.Client() 66 client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) 67 68 t.Assert(client.GetContent(ctx, "/"), "Not Found") 69 t.Assert(client.GetContent(ctx, "/api.v2"), "Not Found") 70 t.Assert(client.GetContent(ctx, "/api.v2/test"), "1test2") 71 t.Assert(client.GetContent(ctx, "/api.v2/hook"), "hook any") 72 t.Assert(client.GetContent(ctx, "/api.v2/hook/name"), "hook namehook any") 73 t.Assert(client.GetContent(ctx, "/api.v2/hook/name/any"), "hook any") 74 t.Assert(client.GetContent(ctx, "/api.v2/order/list"), "1list2") 75 t.Assert(client.GetContent(ctx, "/api.v2/order/update"), "Not Found") 76 t.Assert(client.PutContent(ctx, "/api.v2/order/update"), "1update2") 77 t.Assert(client.GetContent(ctx, "/api.v2/user/drop"), "Not Found") 78 t.Assert(client.DeleteContent(ctx, "/api.v2/user/drop"), "1drop2") 79 t.Assert(client.GetContent(ctx, "/api.v2/user/edit"), "Not Found") 80 t.Assert(client.PostContent(ctx, "/api.v2/user/edit"), "1edit2") 81 t.Assert(client.GetContent(ctx, "/api.v2/user/info"), "1info2") 82 }) 83 }