From 173e12dcf79785e37931c6b06e944081229db2a3 Mon Sep 17 00:00:00 2001 From: miloud Date: Fri, 23 Feb 2024 00:45:30 +0100 Subject: [PATCH 1/2] added feat gethandler name --- gin.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/gin.go b/gin.go index 24a9864a..ce0f2f34 100644 --- a/gin.go +++ b/gin.go @@ -291,6 +291,22 @@ func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } +// GetHandlerPath takes a name of a handler and returns a slice of matched paths associated with that handler. +func (engine *Engine) GetHandlerPath(handlerName string) []string { + handlers := engine.Routes() + var paths []string + + for _, f := range handlers { + handler := strings.Split(f.Handler, ".") + + if handler[len(handler)-1] == handlerName { + paths = append(paths, f.Path) + } + } + + return paths +} + // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers From ae04cc6576d8a33d3a6d0bba2a21818ef9040af2 Mon Sep 17 00:00:00 2001 From: miloud Date: Fri, 23 Feb 2024 00:57:48 +0100 Subject: [PATCH 2/2] added GetHandlerPath test --- gin_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/gin_test.go b/gin_test.go index 8825ac7e..16b5f27c 100644 --- a/gin_test.go +++ b/gin_test.go @@ -676,6 +676,24 @@ func TestPrepareTrustedCIRDsWith(t *testing.T) { } } +func TestGetHandlerPath(t *testing.T) { + r := New() + r.GET("/foo", handlerTest1) + r.POST("/bar", handlerTest2) + + v := r.Group("/users") + { + v.GET("/:id1", handlerTest1) + v.POST("/:id2", handlerTest2) + } + + p1 := r.GetHandlerPath("handlerTest1") + assert.Equal(t, p1, []string{"/foo", "/users/:id1"}) + + p2 := r.GetHandlerPath("handlerTest2") + assert.Equal(t, p2, []string{"/bar", "/users/:id2"}) +} + func parseCIDR(cidr string) *net.IPNet { _, parsedCIDR, err := net.ParseCIDR(cidr) if err != nil {