From 74fe36fa484deba4f9fa2ef8683c6223b5294acd Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Sun, 7 Jun 2015 13:49:36 +0200 Subject: [PATCH] Routes() returns the function name of the main handler --- debug.go | 2 +- gin.go | 32 ++++++++++++++++++++------------ 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/debug.go b/debug.go index a0b99f43..e5b39cc2 100644 --- a/debug.go +++ b/debug.go @@ -16,7 +16,7 @@ func IsDebugging() bool { func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) - handlerName := nameOfFunction(handlers[nuHandlers-1]) + handlerName := nameOfFunction(handlers.Last()) debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } } diff --git a/gin.go b/gin.go index 5a87d566..30c43202 100644 --- a/gin.go +++ b/gin.go @@ -62,11 +62,20 @@ type ( } RouteInfo struct { - Method string - Path string + Method string + Path string + Handler string } ) +func (c HandlersChain) Last() HandlerFunc { + length := len(c) + if length > 0 { + return c[length-1] + } + return nil +} + // Returns a new blank Engine instance without any middleware attached. // The most basic configuration func New() *Engine { @@ -176,23 +185,22 @@ func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { 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, - }) - } + routes = iterate("", tree.method, routes, tree.root) } return routes } -func iterate(path string, routes []string, root *node) []string { +func iterate(path, method string, routes []RouteInfo, root *node) []RouteInfo { path += root.path - if root.handlers != nil { - routes = append(routes, path) + if len(root.handlers) > 0 { + routes = append(routes, RouteInfo{ + Method: method, + Path: path, + Handler: nameOfFunction(root.handlers.Last()), + }) } for _, node := range root.children { - routes = iterate(path, routes, node) + routes = iterate(path, method, routes, node) } return routes }