Routes() returns the function name of the main handler

This commit is contained in:
Manu Mtz-Almeida 2015-06-07 13:49:36 +02:00
parent c7d2d82d01
commit 74fe36fa48
2 changed files with 21 additions and 13 deletions

View File

@ -16,7 +16,7 @@ func IsDebugging() bool {
func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {
if IsDebugging() { if IsDebugging() {
nuHandlers := len(handlers) nuHandlers := len(handlers)
handlerName := nameOfFunction(handlers[nuHandlers-1]) handlerName := nameOfFunction(handlers.Last())
debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)
} }
} }

28
gin.go
View File

@ -64,9 +64,18 @@ type (
RouteInfo struct { RouteInfo struct {
Method string Method string
Path 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. // Returns a new blank Engine instance without any middleware attached.
// The most basic configuration // The most basic configuration
func New() *Engine { func New() *Engine {
@ -176,23 +185,22 @@ func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
func (engine *Engine) Routes() (routes []RouteInfo) { func (engine *Engine) Routes() (routes []RouteInfo) {
for _, tree := range engine.trees { for _, tree := range engine.trees {
for _, path := range iterate("", nil, tree.root) { routes = iterate("", tree.method, routes, tree.root)
routes = append(routes, RouteInfo{
Method: tree.method,
Path: path,
})
}
} }
return routes return routes
} }
func iterate(path string, routes []string, root *node) []string { func iterate(path, method string, routes []RouteInfo, root *node) []RouteInfo {
path += root.path path += root.path
if root.handlers != nil { if len(root.handlers) > 0 {
routes = append(routes, path) routes = append(routes, RouteInfo{
Method: method,
Path: path,
Handler: nameOfFunction(root.handlers.Last()),
})
} }
for _, node := range root.children { for _, node := range root.children {
routes = iterate(path, routes, node) routes = iterate(path, method, routes, node)
} }
return routes return routes
} }