feat: Add GetRoutes (#2112)

feat: Add GetRoutes
pull/2128/head
kinggo 2022-09-27 15:02:38 +08:00 committed by GitHub
parent cc1e9bf115
commit ff348b5e92
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

18
app.go
View File

@ -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 "/").
//

View File

@ -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)
}
}