diff --git a/app.go b/app.go index 033de56cdf..9b1fa9a67a 100644 --- a/app.go +++ b/app.go @@ -638,6 +638,24 @@ func (app *App) GetRoute(name string) Route { return Route{} } +// GetRoutes Get all routes. When filterUseOption equal to true, it will filter the routes registered by the middleware. +func (app *App) GetRoutes(filterUseOption ...bool) []Route { + var rs []Route + var filterUse bool + if len(filterUseOption) != 0 { + filterUse = filterUseOption[0] + } + 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 9c12963868..ec9224dbc2 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) + } + +}