There is an issue with routing requests when utilizing the group() method. When registering routes without group() the router is working as expected.
When registering a route in a sub-router the url path should be mapped to the registered handler method.
See the provided example code.
Run the applicatins and start requests.
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func adminIndex(c echo.Context) error {
return c.String(http.StatusOK, "Hello, Admin!")
}
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.GET("/admin*", adminIndex)
e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123" {
return true, nil
}
return false, nil
}))
e.Logger.Fatal(e.Start(":1323"))
}
HTTP client: $ curl http://localhost:1323/admin/ --basic --user joe:123
Output: Hello, Admin!
HTTP client: $ curl http://localhost:1323/admin/4 --basic --user joe:123
Output: Hello, Admin!
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func adminIndex(c echo.Context) error {
return c.String(http.StatusOK, "Hello, Admin!")
}
func main() {
e := echo.New()
//e.Pre(middleware.RemoveTrailingSlash())
//e.Pre(middleware.AddTrailingSlash())
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
admin := e.Group("/admin")
admin.GET("", adminIndex)
admin.GET("/*", adminIndex)
admin.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123" {
return true, nil
}
return false, nil
}))
e.Logger.Fatal(e.Start(":1323"))
}
Echo v3.2.3 and Golang 1.9.
Move your middleware before you define any handler and it should work.
Thank you for your comments.
You should define middleware first and then any handlers. So, in your example admin.Use should come before admin.GET.
Most helpful comment
Move your middleware before you define any handler and it should work.