NotFoundHandler: panic: echo: unknown handler
The following code fails with panic: echo: unknown handler line 16: e.NotFoundHandler(index)
package main
import (
"net/http"
"github.com/labstack/echo"
)
func index(c *echo.Context) {
c.HTML(http.StatusOK, "<html></html>")
}
func main() {
e := echo.New()
e.NotFoundHandler(index)
e.Run(":1234")
}
I have an older version of echo (54d2f7236826e28baf1d41db77dfc162e27246cf) and with that the code above works just fine. Could this be a bug or am I missing something?
It's not a bug, support for fun(*echo.Context) was dropped lately to encourage use of echo.HandlerFunc which focuses on centralized HTTP error handling using echo.HTTPErrorHandler
Even if I use echo.HandlerFunc it throws the exact same error for me.
If you get the latest, it should work. echo.HandlerFunc was refactored in https://github.com/labstack/echo/releases/tag/v0.0.12
I must be dumb, but even with that release it doesn't work. :)
I've checked echo_test.go and I saw it uses func(c *Context) *HTTPError for NotFoundHandler. Changing the code to
func index(c *echo.Context) *echo.HTTPError {
return c.HTML(http.StatusOK, "<html></html>")
}
makes it work, but I'm just not sure anymore if this is the right way.
This is the right way, by doing so you don't have to deal with errors as it's taken care by echo.HTTPErrorHandler (which can be customized) - all you do is return them as echo.*HTTPError. For concrete examples, you can explore examples directory in the repository.
Okay, thanks!