Skip to content

Commit

Permalink
List of routes
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat committed Jun 7, 2015
1 parent 042046e commit 45dd777
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
28 changes: 28 additions & 0 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ type (
// handler.
HandleMethodNotAllowed bool
}

RouteInfo struct {
Method string
Path string
}
)

// Returns a new blank Engine instance without any middleware attached.
Expand Down Expand Up @@ -169,6 +174,29 @@ func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
root.addRoute(path, handlers)
}

func (engine *Engine) Routes() (routes []RouteInfo) {
for _, tree := range engine.trees {
for _, path := range iterate("", nil, tree.root) {
routes = append(routes, RouteInfo{
Method: tree.method,
Path: path,
})
}
}
return routes
}

func iterate(path string, routes []string, root *node) []string {
path += root.path
if root.handlers != nil {
routes = append(routes, path)
}
for _, node := range root.children {
routes = iterate(path, routes, node)
}
return routes
}

// The router is attached to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine undefinitelly unless an error happens.
Expand Down
48 changes: 47 additions & 1 deletion gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
//TODO
// func (engine *Engine) LoadHTMLGlob(pattern string) {
// func (engine *Engine) LoadHTMLFiles(files ...string) {
// func (engine *Engine) Run(addr string) error {
// func (engine *Engine) RunTLS(addr string, cert string, key string) error {

func init() {
Expand Down Expand Up @@ -180,3 +179,50 @@ func compareFunc(t *testing.T, a, b interface{}) {
t.Error("different functions")
}
}

func TestListOfRoutes(t *testing.T) {
handler := func(c *Context){}
router := New()
router.GET("/favicon.ico", handler)
router.GET("/", handler)
group := router.Group("/users")
{
group.GET("/", handler)
group.GET("/:id", handler)
group.POST("/:id", handler)
}
router.Static("/static", ".")

list := router.Routes()

assert.Len(t, list, 7)
assert.Contains(t, list, RouteInfo{
Method: "GET",
Path: "/favicon.ico",
})
assert.Contains(t, list, RouteInfo{
Method: "GET",
Path: "/",
})
assert.Contains(t, list, RouteInfo{
Method: "GET",
Path: "/users/",
})
assert.Contains(t, list, RouteInfo{
Method: "GET",
Path: "/users/:id",
})
assert.Contains(t, list, RouteInfo{
Method: "POST",
Path: "/users/:id",
})
assert.Contains(t, list, RouteInfo{
Method: "GET",
Path: "/static/*filepath",
})
assert.Contains(t, list, RouteInfo{
Method: "HEAD",
Path: "/static/*filepath",
})

}

0 comments on commit 45dd777

Please sign in to comment.