Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added GetHandlerPath #3853

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions gin.go
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions gin_test.go
Expand Up @@ -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 {
Expand Down