echo: Custom timeout middleware changes behavior of code

I could totally be thinking about this thing wrong and have the wrong mental model but in this simplified configuration, I’m getting weird behavior:

package main

import (
	"errors"
	"log"
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

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

	timeoutMW1 := middleware.Timeout()

	// from docs: https://echo.labstack.com/docs/middleware/timeout
	timeoutMW2 := middleware.TimeoutWithConfig(middleware.TimeoutConfig{
		Skipper:      middleware.DefaultSkipper,
		ErrorMessage: "custom timeout error message returns to client",
		OnTimeoutRouteErrorHandler: func(err error, c echo.Context) {
			log.Println(c.Path())
		},
		Timeout: 30 * time.Second,
	})

	e.GET("/do1", hello, timeoutMW1, authenticate)
	e.GET("/do2", hello, timeoutMW2, authenticate)

	e.Start(":8080")
}

type customError struct {
	Message string `json:"message"`
}

func authenticate(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		authHeader := c.Request().Header.Get("Authorization")
		if authHeader != "secret" {
			c.JSON(http.StatusUnauthorized, customError{Message: "unauthorized"})

			return errors.New("unauthorized")
		}

		return next(c)
	}
}

func hello(c echo.Context) error {
	return c.JSON(http.StatusOK, "hello")
}

/do1 will return as expected but /do2 will respond with a 200 and have no body

Maybe where I’m wrong in my thoughts is responding in the authenticate middleware. Essentially I want to have that middleware respond but I also want to return up the error so that other middlewares above can get that error (e.g. logging middleware). Is this not the right way to go about this?

To me it seems more like a problem with that custom timeout middleware. I don’t understand why having the custom one would act any different than the middleware.Timeout() one.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 22 (12 by maintainers)

Most upvoted comments

@aldas I follow but it’s not obvious to me why 200 is sent rather than 401 there, and it seems like @thestephenstanton isn’t sure either