labstack / echo

High performance, minimalist Go web framework
https://echo.labstack.com
MIT License
29.87k stars 2.23k forks source link

Group middleware does not work for "Any" route #2517

Open KaymeKaydex opened 1 year ago

KaymeKaydex commented 1 year ago

Issue Description

Checklist

Expected behaviour

normal routing

Actual behaviour

{ "message": "Not Found" }

Steps to reproduce

just create any request

Working code to debug

    g := e.Group("/api/test") 
    g.Use(echo.WrapMiddleware(mw.NewMW()))
    {
        g.Any("*", testController.Proxy) 
    }

actual result is 
{
    "message": "Not Found"
}
but route cant return anything

Version/commit

github.com/labstack/echo/v4 v4.11.1

aldas commented 1 year ago

This is little bit tricky.

Let assume group and handler is added like this:

func main() {
    e := echo.New()

    g := e.Group("/api/test")
    //g.Use(middleware.Logger())
    g.Any("*", func(c echo.Context) error {
        return c.String(http.StatusOK, c.Path())
    })

    if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) {
        e.Logger.Fatal(err)
    }
}

When you add route with g.Any("*" you will end up with route path /api/test*. This will match both of following request

x@x:~/code$ curl http://localhost:8080/api/test/hi
/api/test*
x@x:~/code$ curl http://localhost:8080/api/testhi
/api/test*

as your router has following routes image

now when we add middleware to that group by uncommenting g.Use(middleware.Logger())

we have following routes image

that 4 is 404 route for path /api/test/* which is causing problem here as it is more precise match than api/test*.

x@x:~/code$ curl http://localhost:8080/api/testhi
/api/test*
x@x:~/code$ curl http://localhost:8080/api/test/hi
{"message":"Not Found"}

As a workaround I suggest:

That 404 route is a "feature" that is added here (line 32) https://github.com/labstack/echo/blob/77d5ae6a9173d89c49e008607d08df7ba41336f0/group.go#L21-L32