Merge ae04cc6576d8a33d3a6d0bba2a21818ef9040af2 into 8763f33c65f7df8be5b9fe7504ab7fcf20abb41d

This commit is contained in:
MiloudB 2025-03-23 09:41:18 +08:00 committed by GitHub
commit 06601b35e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 0 deletions

16
gin.go
View File

@ -299,6 +299,22 @@ func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {
engine.FuncMap = 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. // NoRoute adds handlers for NoRoute. It returns a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) { func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.noRoute = handlers engine.noRoute = handlers

View File

@ -716,6 +716,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 { func parseCIDR(cidr string) *net.IPNet {
_, parsedCIDR, err := net.ParseCIDR(cidr) _, parsedCIDR, err := net.ParseCIDR(cidr)
if err != nil { if err != nil {