Router tree bug

when add a catch-all router, there may be an error reported:

panic: runtime error: index out of range [0] with length 0

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.GET("/static/", func(c *gin.Context) { c.String(200, "static") })
    r.GET("/static/*file", func(c *gin.Context) { c.String(200, "static file") })

    r.Run()
}

Source code

tree.go

        if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
            pathSeg := strings.SplitN(n.children[0].path, "/", 2)[0]
            panic("catch-all wildcard '" + path +
                "' in new path '" + fullPath +
                "' conflicts with existing path segment '" + pathSeg +
                "' in existing prefix '" + n.path + pathSeg +
                "'")
        }

this line pathSeg := strings.SplitN(n.children[0].path, "/", 2)[0]

actually, n node do not have any children.

Environment

  • go version: go1.20
  • gin version (or commit ref): v1.9.1
  • operating system: mac os

Comment From: cainmusic

i thought: if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { should be i == 0 n.children[0].path should be n.path

Comment From: FirePing32

The below line expects that the path will end with a wildcard name. https://github.com/gin-gonic/gin/blob/53fbf4dbfbf465b552057e6f8d199a275151b7a1/tree.go#L354 /static/*file is already a catch-all wildcard. You are trying to initialize a path /static/ (notice the trailing slash). This path is already a type of catch-all wildcard with no child paths, which leads to the conflict. WIll open a PR by today EOD to fix this.