-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Closed
Description
Issue Description
When use echo.NewHTTPError
to generate HTTP errors in the API handler, the status code read in the middleware is not set properly. This behavior differs from c.JSON
Checklist
- Dependencies installed
- No typos
- Searched existing issues and docs
Expected behaviour
The c.Response().Status
should set to the value returned with the echo.NewHTTPError
Actual behaviour
c.Response().Status
is always 200
Steps to reproduce
Below is an example to reproduce the issue and shows the different results observed using echo.NewHTTPErro
v.s. c.JSON
in an API handler
Working code to debug
package main
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
)
var e *echo.Echo
func Logger(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
defer func() {
resp := c.Response()
e.Logger.Infof("URI: %v; Resp code: %v", c.Request().URL, resp.Status)
}()
return next(c)
}
}
func main() {
e = echo.New()
e.Logger.SetLevel(log.DEBUG)
e.Use(Logger)
e.GET("/test1", func(c echo.Context) error {
return c.JSON(http.StatusNotFound, "test 1")
})
e.GET("/test2", func(_ echo.Context) error {
return echo.NewHTTPError(http.StatusNotFound, "test 2")
})
log.Panic(e.Start(":8080"))
}
Access the server with curl http://localhost:8080/test1
& curl http://localhost:8080/test
gets results as
{"time":"2021-04-08T00:18:21.68735263+08:00","level":"INFO","prefix":"echo","file":"main.go","line":"15","message":"URI: /test1; Resp code: 404"}
{"time":"2021-04-08T00:18:24.795359144+08:00","level":"INFO","prefix":"echo","file":"main.go","line":"15","message":"URI: /test2; Resp code: 200"}
Version/commit
echo version: v4.2.1
go version: go1.16.3 linux/amd64