From 92221f5c6d57053484c22184c8b0155185c93bb9 Mon Sep 17 00:00:00 2001 From: kinggo Date: Thu, 22 Sep 2022 13:01:40 +0800 Subject: [PATCH] feat: Add GetRoutes --- app.go | 14 ++++++++++++++ app_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/app.go b/app.go index 033de56cdff..9be92209f74 100644 --- a/app.go +++ b/app.go @@ -638,6 +638,20 @@ func (app *App) GetRoute(name string) Route { return Route{} } +// GetRoutes Get all routes,when filterUse equal to true.it will filter the routes registered by the middleware. +func (app *App) GetRoutes(filterUse bool) []Route { + var rs []Route + for _, routes := range app.stack { + for _, route := range routes { + if filterUse && route.use { + continue + } + rs = append(rs, *route) + } + } + return rs +} + // Use registers a middleware route that will match requests // with the provided prefix (which is optional and defaults to "/"). // diff --git a/app_test.go b/app_test.go index 9c129638686..ec9224dbc26 100644 --- a/app_test.go +++ b/app_test.go @@ -1647,3 +1647,33 @@ func Test_App_SetTLSHandler(t *testing.T) { utils.AssertEqual(t, "example.golang", c.ClientHelloInfo().ServerName) } + +func TestApp_GetRoutes(t *testing.T) { + app := New() + app.Use(func(c *Ctx) error { + return c.Next() + }) + handler := func(c *Ctx) error { + return c.SendStatus(StatusOK) + } + app.Delete("/delete", handler).Name("delete") + app.Post("/post", handler).Name("post") + routes := app.GetRoutes(false) + utils.AssertEqual(t, 11, len(routes)) + methodMap := map[string]string{"/delete": "delete", "/post": "post"} + for _, route := range routes { + name, ok := methodMap[route.Path] + if ok { + utils.AssertEqual(t, name, route.Name) + } + } + + routes = app.GetRoutes(true) + utils.AssertEqual(t, 2, len(routes)) + for _, route := range routes { + name, ok := methodMap[route.Path] + utils.AssertEqual(t, true, ok) + utils.AssertEqual(t, name, route.Name) + } + +}